yield作為python內置關鍵字,譯為生產。在函數中可暫時認為 return 的替代品。
如果某函數包含 yield,直接調用此函數時,函數並不直接執行函數邏輯,而是返回一個generator。 通過調用 generator.next() 或 item (for循環) 觸發函數執行,執行到yield時,可視為返回yield后的值。
其好處在於在需要結果時才執行獲取,不必提前申請過多內存信息來存取處理結果列表。
(日常開發不太用,源碼中比較常見,調用接口時需要捋清使用方法)
yield代碼簡單示例(斐波那契)
def fab(max): n, a, b = 0, 0, 1 while n < max: print b a, b = b, a + b n = n + 1 fab(6)
輸出:
1
1
2
3
然后我們將使用 yeild 聲明 b, 相當於每次調用fab時,返回b。 代碼如下
def fab_yield(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1
# 函數返回生成器,並不會觸發邏輯執行 generator = fab_yield(4) # 為了更容易理解,調用4個.next來獲取數據,日常可以直接使用for i in fab_yield
print(y.next()) print(y.next()) print(y.next()) print(y.next())
# 多余的next調用會StopIteration異常
輸出:
1
1
2
3
上面提到使用 for i in fab_yield()同樣可以取出數據,那順帶一下python中for循環的原理
python for 原理
python中可迭代的對象很多。列表、元組、字典等都可以,這些對象必須都有 __iter__ 和 next 方法。
其中__iter__返回一個Iterator(類似生成器),使用for遍歷對象時相當於調用__iter__獲取一個Iterator,然后調用 next 遍歷數據。
for 流程驗證用例:
class Te: def __init__(self): self.a = 0 def __iter__(self): print("call iter") return self def next(self): print("call next") if self.a >= 3: raise StopIteration() self.a += 1 return self.a t=Te() for i in t: print(i) 輸出: call iter call next 1 call next 2 call next 3 call next