yield dùng trong generator. Để hiểu, trước hết xem iterable: list, file, string... có thể traverse bằng for ... in. Iterator là iterable nhưng chỉ iterate một lần. Lấy iterator từ iterable bằng iter(), có method next() (Python 2) / __next__() (Python 3).
Generator
Generator giống function nhưng yield lần lượt các item trong iterator.
- Gọi generator function → trả về iterator object, chưa thực thi function
- Gọi
next()lần đầu → function chạy đếnyield, trả giá trị yieldnhớ vị trí, lầnnext()sau tiếp tục từ đó
Ví dụ: Fibonacci generator
import sys
def fibo(n):
a, b = 0, 1
while True:
if a > n:
return
yield a
a, b = b, a + b
f = fibo(20)
while True:
try:
print(next(f))
except StopIteration:
sys.exit()
Kết quả
0 1 1 2 3 5 8 13
Lợi ích: Lazy evaluation, tiết kiệm memory, xử lý stream dữ liệu lớn/vô hạn.