return 的作用
在一个 generator function 中,如果没有 return,则默认执行至函数完毕,如果在执行过程中 return,则直接抛出 StopIteration 终止迭代。
def func():
a = 0
b = 1
while True:
if b >= 5:
return
yield b
a, b = b, a + b
f = func()
while True:
print(next(f))
# 结果:
# 1
# 1
# 2
# 3
# ---------------------------------------------------------------------------
# StopIteration Traceback (most recent call last)
# <ipython-input-4-3a2f06d59b2d> in <module>
# 9 f = func()
# 10 while True:
# ---> 11 print(next(f))
#
# StopIteration:
所以,想要使for迭代终止,可以在generator function中使用两种方式,一种是while+条件,第二种就是使用return语句。
return方式:
def func():
a = 0
b = 1
while True:
# 当b等于5时终止
if b >= 5:
return
yield b
a, b = b, a + b
f = func()
for i in f:
print(i)
1
1
2
3
while+条件:
def func(max):
n = 0
a = 0
b = 1
while n < max:
yield b
a, b = b, a + b
n += 1
f = func(3)
for i in f:
print(i)
1
1
2
用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