yield 將普通函數轉變為生成器,實現惰性求值與常數記憶體迭代。本文從斐波那契數列演進,層層剖析 yield 的執行流程與優勢。
def fab(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n += 1
def fab(max):
n, a, b = 0, 0, 1
L = []
while n < max:
L.append(b)
a, b = b, a + b
n += 1
return L
class Fab:
def __init__(self, max):
self.max, self.n, self.a, self.b = max, 0, 0, 1
def __iter__(self):
return self
def __next__(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n += 1
return r
raise StopIteration()
def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b # 暫停並產出值
a, b = b, a + b
n += 1
呼叫 fab(5) 不會立即執行函數體,而是返回一個生成器物件。每次迭代(或呼叫 next())才會執行到下一個 yield,並保留區域變數狀態:
>> f = fab(5)
>>> next(f) # 1
>>> next(f) # 1
>>> next(f) # 2
>>> next(f) # 3
>>> next(f) # 5
>>> next(f) # StopIteration
yield 之間自動保存/恢復。for 迴圈,自動處理 StopIteration。fab 是生成器函數,fab(5) 是生成器實例。from inspect import isgeneratorfunction
isgeneratorfunction(fab) # True
import types
isinstance(fab, types.GeneratorType) # False
isinstance(fab(5), types.GeneratorType) # True
在生成器函數中 return(或隱含結束)會拋出 StopIteration 終止迭代;return value(Python 3.3+)會將 value 附加在 StopIteration.value 中供捕獲。