Trung BìnhPython iconPython

Generators vs Iterators — khác nhau như thế nào? `__iter__` và `__next__`?

Iterator: bất kỳ object nào implement __iter__()__next__(). Generator: function dùng yield — tự động implement iterator protocol, lazy, stateful.

python
# Class-based Iterator
class CountDown:
    def __init__(self, start): self.current = start

    def __iter__(self): return self  # Trả về chính nó

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

list(CountDown(3))  # [3, 2, 1]

# Generator function — ngắn gọn hơn
def countdown(n):
    while n > 0:
        yield n
        n -= 1

# Generator expression — lazy (khác list comprehension)
gen = (x**2 for x in range(1_000_000))  # Không chiếm RAM

Generator với send() — coroutine-lite, nhận value từ caller:

python
def accumulator():
    total = 0
    while True:
        value = yield total  # Nhận value từ .send()
        if value is None: break
        total += value

acc = accumulator()
next(acc)          # Khởi động generator
acc.send(10)       # 10
acc.send(20)       # 30

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python