python中的迭代器对象符合迭代器协议,这基本上意味着它们提供了两种方法:
__iter__()和
__next__()。
在
__iter__
返回迭代器对象,并在循环开始时隐式调用。该
__next__()
方法返回下一个值,并在每次循环增量时隐式调用。当没有更多值要返回时,此方法将引发StopIteration
异常,该异常由循环构造以停止迭代的方式隐式捕获。
这是一个简单的计数器示例:
class Counter: def __init__(self, low, high): self.current = low - 1 self.high = high def __iter__(self): return self def __next__(self): # Python 2: def next(self) self.current += 1 if self.current < self.high: return self.current raise StopIterationfor c in Counter(3, 9): print(c)
这将打印:
345678
如上一个答案所述,使用生成器编写起来更容易:
def counter(low, high): current = low while current < high: yield current current += 1for c in counter(3, 9): print(c)
打印的输出将相同。在内部,生成器对象支持迭代器协议,并且执行与类Counter大致相似的操作。
David Mertz的文章
Iterators和
Simple Generators是很好的介绍。



