Python 生成器是一種特殊的迭代器,它允許函數透過 yield 關鍵字逐步產生一系列值,而不是一次性返回所有結果。這種「惰性求值」特性讓生成器在處理大量數據或無限序列時極為高效,記憶體佔用極低。
定義生成器函數只需在函數體中使用 yield 而非 return:
def countdown(n):
print("Counting down")
while n > 0:
yield n
n -= 1
調用生成器函數不會立即執行代碼,而是返回一個生成器對象:
>>> c = countdown(5)
>>> c.__next__() # Python 3 使用 __next__()
Counting down
5
>>> c.__next__()
4
>>> c.__next__()
3
關鍵機制:每次調用 next(),函數執行到下一個 yield 暫停並返回值;再次調用時從暫停處繼續執行,直到函數結束拋出 StopIteration。
實際開發中通常配合 for 循環使用,自動處理迭代與異常:
>>> for i in countdown(5):
... print(i)
...
Counting down
5
4
3
2
1
send(value) 可向生成器傳遞數據,使 yield 表達式獲得返回值:
def h(n):
while n > 0:
m = (yield n)
print(f"m is {m}")
n -= 1
print(f"n is {n}")
>>> p = h(5)
>>> p.__next__() # 首次必須用 next() 或 send(None)
5
>>> p.__next__() # 相當於 send(None)
m is None
n is 4
4
>>> p.send("test") # 傳遞 "test" 給 yield 表達式
m is test
n is 3
3
區別:next() 相當於 send(None);send() 允許外部注入數據,實現協程雛形。
send()/throw()/close() 實現複雜控制流生成器是 Python 編寫高效、優雅代碼的利器,掌握其核心機制能顯著提升程序設計能力。