https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/
https://blog.csdn.net/mieleizhi0522/article/details/82142856
使用yield()的好处是节省内存占用, 同时不需要大量改动代码. yield使函数变成generator, 可通过for循环或者next()方法迭代输出, 函数中有return则raise StopIteration自动终止迭代.
注意: 写成res = yield b
时b会直接输出出去, 再调用generator的next()方法时函数从yield处继续执行, 此时赋值给res的是None, 每次调用next()都是从上次中断的地方继续执行. 如果想要给res赋值使用generator的send()方法, 该方法包含了next()的作用, 使函数再次运行到yield关键字处停止.
def foo():
print("starting...")
while True:
res = yield 4
print("res:",res)
g = foo()
print(next(g))
# starting...
# 4
print("*"*20)
# ********************
print(g.send(7))
# res: 7
# 4 # 从上一次yield中断的地方再次运行到yield处
使用yield实现缓冲区读取文件, 避免内存溢出:
def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath, 'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return
网友评论