← 中文资源

简体中文版本

自定义迭代器实现 __iter__ 与 __next__

类实现 __iter__ 返回自身、__next__ 逐页递进并在末尾抛 StopIteration,就能被 for 循环、iter() 与 next() 像内建序列一样驱动,新的实例从头重读。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

page: ['user1', 'user2']
page: ['user3']
page: ['user4', 'user5']
manual: ['user1', 'user2'] ['user3']
second pass: ['user1', 'user2', 'user3', 'user4', 'user5']

实现说明

主要代码集中在 Cursor和函数 __init__、__iter__、__next__。 在这里做循环的是 for page in Cursor(pages)。代码不会带着坏状态静默继续,守卫一命中就抛 StopIteration。

使用要点

  • 守卫 self.position >= len(self.pages) 成立时借助提前的 raise 直接离开。
  • 直接运行文件,输出会带上标签,比如 page:、manual:、second pass:——输出的每一行都能指回产生它的那次调用。

常见问题

前置条件不成立会发生什么?

守卫处(self.position >= len(self.pages))会抛出 StopIteration,非法状态到不了主逻辑。

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 __init__、__iter__、__next__。

主要签名是 def __init__(self, pages)

核心语句

def __init__(self, pages):
    self.pages = pages
    self.position = 0
def __iter__(self):
    # Returning self lets for-loops drive this same object.
    return self
def __next__(self):
    if self.position >= len(self.pages):
        raise StopIteration  # Ending the loop is the iterator's job.
    page = self.pages[self.position]
    self.position += 1
    return page

代码示例

class Cursor:
    """Iterate in-memory pages the way a paged endpoint hands out pages."""

    def __init__(self, pages):
        self.pages = pages
        self.position = 0

    def __iter__(self):
        # Returning self lets for-loops drive this same object.
        return self

    def __next__(self):
        if self.position >= len(self.pages):
            raise StopIteration  # Ending the loop is the iterator's job.
        page = self.pages[self.position]
        self.position += 1
        return page


pages = [["user1", "user2"], ["user3"], ["user4", "user5"]]

for page in Cursor(pages):
    print("page:", page)

# iter() and next() drive the same protocol by hand.
manual = iter(Cursor(pages))
print("manual:", next(manual), next(manual))

# A fresh Cursor re-reads the same backing list from the start.
second_pass = [row for page in Cursor(pages) for row in page]
print("second pass:", second_pass)