Python学习(七)
发布人:shili8
发布时间:2024-12-27 09:21
阅读次数:0
**Python 学习(七)**
在前六篇文章中,我们已经介绍了 Python 的基本语法、数据类型、控制结构、函数等概念。今天我们将继续讨论一些更高级的主题,包括面向对象编程、异常处理和文件操作。
### 面向对象编程面向对象编程(Object-Oriented Programming, OOP)是计算机科学中的一种编程范式,它以类、对象、继承等概念来组织代码。Python 支持面向对象编程的所有特性。
#### 类和对象在 Python 中,类使用 `class` 关键字定义,而对象则是通过实例化类创建的。
# 定义一个类class Person: def __init__(self, name, age): self.name = name self.age = age# 实例化一个对象person = Person("John",30) print(person.name) # Johnprint(person.age) #30
#### 属性和方法在类中,属性是用来描述对象的特征,而方法则是用来描述对象的行为。
# 定义一个类class Person: def __init__(self, name, age): self.name = name self.age = age # 属性 @property def get_name(self): return self.name # 方法 def say_hello(self): print(f"Hello, my name is {self.name}.") # 实例化一个对象person = Person("John",30) print(person.get_name) # Johnperson.say_hello() # Hello, my name is John.
#### 继承继承是指子类继承父类的属性和方法。
# 定义一个父类class Animal: def __init__(self, name): self.name = name def eat(self): print(f"{self.name} is eating.") # 定义一个子类class Dog(Animal): def __init__(self, name, age): super().__init__(name) self.age = age def bark(self): print(f"{self.name} says Woof!") # 实例化一个对象dog = Dog("John",3) print(dog.name) # Johnprint(dog.age) #3dog.eat() # John is eating. dog.bark() # John says Woof!
### 异常处理异常是指程序在执行过程中出现的错误或异常情况。
#### try-except-finallytry-except-finally 是 Python 中用于异常处理的语句结构。
# try-except-finally语句结构try: # 可能会引发异常的代码 x =1 /0except ZeroDivisionError: # 处理异常的代码 print("Cannot divide by zero.") finally: # 无论是否发生异常,总是执行的代码 print("This code will always be executed.")
#### raiseraise 是用于抛出异常的语句。
# 抛出一个异常def divide(x, y): if y ==0: raise ZeroDivisionError("Cannot divide by zero.") return x / ytry: print(divide(1,0)) except ZeroDivisionError as e: print(e)
### 文件操作文件是计算机中用来存储数据的设备。
#### open()
open() 是用于打开文件的函数。
# 打开一个文件file = open("example.txt", "r") print(file.read()) file.close()
#### read()
read() 是用于读取文件内容的方法。
#读取文件内容with open("example.txt", "r") as file: print(file.read())
#### write()
write() 是用于写入文件内容的方法。
# 写入文件内容with open("example.txt", "w") as file: file.write("Hello, world!")
### 总结在本篇文章中,我们介绍了 Python 中面向对象编程、异常处理和文件操作的相关概念。这些知识对于更高级的编程任务是必不可少的。
### 参考资料* 《Python Cookbook》第3 版* 《Python Crash Course》第2 版