yield关键字:带有yield的函数是一个生成器模板,调用模板会返回一个生成器对象,
执行到 yield a 时,create_num 函数就返回一个迭代值,下次迭代时,代码从 yield a 的下一条语句继续执行
def create_num(num):
a, b = 0, 1
current_num = 0
while current_num < num:
# 遍历create_num返回的生成器时,会阻塞在yield的位置,遍历出的值都是yield后的值
yield a
a, b = b, a + b
current_num += 1
return "ok...."
ob = create_num(10)
while True:
try:
ret = next(ob)
print(ret)
except Exception as ret:
print(ret.value)
break
---------------------------
#0
#1
#1
#2
#3
#5
#8
#13
#21
#34
#ok....
send()迭代生成器,传参给yield
def create_num(all_num):
a, b = 0, 1
current_num = 0
while current_num < all_num:
res = yield a # send的参数就是yield语句的返回值
print("老子是send,强势输出。。。", res)
a, b = b, a + b
current_num += 1
ob= create_num(10)
res = next(ob)
print(res)
res = ob.send("老子是send")
print(res)
-------------------
#0
#老子是send,强势输出。。。 老子是send
#1
另一个 yield 的例子来源于文件读取。如果直接对文件对象调用 read() 方法,会导致不可预测的内存占用。好的方法是利用固定长度的缓冲区来不断读取文件内容。通过 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