九. 文件与数据持久化
9.1 读写文本文件
# 写
with open("test.txt", "w", encoding="utf-8") as f:
f.write("第一行\n")
f.write("第二行\n")
# 追加
with open("test.txt", "a", encoding="utf-8") as f:
f.write("追加的行\n")
# 读所有
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 按行读(推荐)
with open("test.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
9.2 CSV 文件操作
import csv
# 写入
data = [["姓名", "年龄"], ["张三", 25], ["李四", 30]]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(data)
# 读取
with open("people.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
9.3 JSON 数据交换格式
import json
# 字典转 JSON 字符串
person = {"name": "王五", "age": 28, "hobby": ["读书", "跑步"]}
json_str = json.dumps(person, ensure_ascii=False, indent=2)
print(json_str)
# 保存到文件
with open("person.json", "w", encoding="utf-8") as f:
json.dump(person, f, ensure_ascii=False, indent=2)
# 读取 JSON
with open("person.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["name"])
十. 异常处理
10.1 基本 try-except
try:
num = int(input("请输入整数: "))
result = 100 / num
print(result)
except ValueError:
print("输入的不是有效整数")
except ZeroDivisionError:
print("不能除以零")
except Exception as e:
print(f"其他错误: {e}")
else:
print("没有发生异常") # try 成功时执行
finally:
print("无论如何都会执行") # 清理资源等
10.2 抛出异常与自定义异常
def withdraw(balance, amount):
if amount > balance:
raise ValueError("余额不足")
return balance - amount
# 自定义异常类
class NegativeAmountError(Exception):
pass
def deposit(amount):
if amount < 0:
raise NegativeAmountError("存款金额不能为负")
10.3 assert 断言(调试用)
def divide(a, b):
assert b != 0, "除数不能为零"
return a / b
# 运行时可用 -O 参数禁用断言
十一. 面向对象编程
11.1 类与对象回顾
class Student:
school = "第一中学" # 类属性,所有实例共享
def __init__(self, name, score):
self.name = name # 实例属性
self.score = score
def introduce(self):
print(f"{self.name} 来自 {self.school}")
s1 = Student("小明", 90)
s1.introduce()
11.2 属性装饰器(@property)
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("半径不能为负")
self._radius = value
@property
def area(self):
return 3.14 * self._radius ** 2
c = Circle(5)
print(c.area) # 像属性一样访问,无需括号
c.radius = 10 # 使用 setter
11.3 类方法与静态方法
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_str):
# 类方法用于创建实例的替代构造函数
year, month, day = map(int, date_str.split("-"))
return cls(year, month, day)
@staticmethod
def is_valid(year, month, day):
# 静态方法,不依赖实例或类
return 1 <= month <= 12 and 1 <= day <= 31
d = Date.from_string("2025-12-25")
print(Date.is_valid(2025, 13, 1)) # False
11.4 继承与 super()
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # 调用父类初始化
self.breed = breed
def speak(self):
return f"{self.name} 汪汪叫"
class Cat(Animal):
def speak(self):
return f"{self.name} 喵喵喵"
animals = [Dog("旺财", "金毛"), Cat("咪咪")]
for a in animals:
print(a.speak())
11.5 魔术方法(双下划线方法)
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __len__(self):
return 2
v1 = Vector(1,2)
v2 = Vector(3,4)
print(v1 + v2) # Vector(4,6)
print(len(v1)) # 2