python3 高级话题
python3 高级话题
python3 高级话题 : 装饰器,with,contextlib, yield, super()
Python3 生成器详解
生成器(Generator)是 Python 中一种特殊的迭代器,它允许你按需生成值,而不是一次性创建并存储所有值,这在处理大数据集或无限序列时特别有用。
1. 生成器基础
创建生成器函数
使用 yield 关键字定义的函数会自动成为生成器函数:
def simple_generator():
yield 1
yield 2
yield 3
# 使用生成器
gen = simple_generator()
print(next(gen)) # 输出: 1
print(next(gen)) # 输出: 2
print(next(gen)) # 输出: 3
生成器表达式
类似于列表推导式,但使用圆括号:
gen_exp = (x**2 for x in range(5))
print(next(gen_exp)) # 输出: 0
print(next(gen_exp)) # 输出: 1
2. 生成器特性
惰性求值
生成器只在需要时才计算和返回值:
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num) # 依次输出 1, 2, 3, 4, 5
状态保持
生成器在每次 yield 后暂停执行,保留所有局部变量状态:
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
print(next(fib)) # 0
print(next(fib)) # 1
print(next(fib)) # 1
print(next(fib)) # 2
3. 高级生成器用法
生成器.send() 方法
可以向生成器发送数据:
def accumulator():
total = 0
while True:
value = yield total
if value is None:
break
total += value
acc = accumulator()
next(acc) # 启动生成器
print(acc.send(10)) # 输出: 10
print(acc.send(20)) # 输出: 30
yield from 语法
简化嵌套生成器的代码:
def chain_generators(*iterables):
for it in iterables:
yield from it
result = list(chain_generators([1, 2], (3, 4), "ab"))
print(result) # [1, 2, 3, 4, 'a', 'b']
协程实现
生成器可用于实现协程:
def coroutine():
while True:
received = yield
print(f"Received: {received}")
co = coroutine()
next(co) # 启动协程
co.send("Hello") # 输出: Received: Hello
co.send("World") # 输出: Received: World
4. 生成器实际应用
处理大文件
def read_large_file(file_path):
with open(file_path, 'r') as f:
for line in f:
yield line.strip()
# 逐行处理大文件,不占用过多内存
for line in read_large_file('huge_file.txt'):
process_line(line)
无限序列
def infinite_sequence():
num = 0
while True:
yield num
num += 1
for i in infinite_sequence():
if i > 100: # 需要终止条件
break
print(i)
管道处理
def generator_pipeline():
nums = (num for num in range(10)) # 生成器表达式
squares = (num**2 for num in nums) # 平方
even = (num for num in squares if num%2==0) # 过滤偶数
for num in even:
yield num
print(list(generator_pipeline())) # [0, 4, 16, 36, 64]
5. 生成器 vs 列表
特性 | 生成器 | 列表 |
---|---|---|
内存使用 | 低 | 高 |
计算时间 | 惰性计算,按需生成 | 立即计算所有元素 |
可重用性 | 只能迭代一次 | 可多次迭代 |
访问方式 | 只能顺序访问 | 可随机访问 |
6. 生成器最佳实践
命名规范:生成器函数名应描述其生成的序列
文档字符串:说明生成器产生的值的类型和意义
异常处理:在生成器内部处理可能的异常
资源清理:使用 try/finally 确保资源释放
def safe_generator(file_path):
try:
with open(file_path) as f:
for line in f:
try:
yield int(line.strip())
except ValueError:
continue
finally:
print("Generator closed")
生成器是 Python 强大而高效的工具,合理使用可以显著提升程序性能,特别是在处理大数据流或实现复杂迭代逻辑时。
https://docs.python.org/3/library/inspect.html
https://blog.csdn.net/NeverLate_gogogo/article/details/107752428
https://tedboy.github.io/python_stdlib/generated/generated/inspect.getmembers.html