如何在 python 中创建一个迭代函数(或迭代器对象)?
最佳答案
python中的迭代器对象符合迭代器协议(protocol),这基本上意味着它们提供了两种方法:__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 StopIteration
for c in Counter(3, 9):
print(c)
这将打印:
3
4
5
6
7
8
使用生成器更容易编写,如上一个答案所述:
def counter(low, high):
current = low
while current < high:
yield current
current += 1
for c in counter(3, 9):
print(c)
打印的输出将是相同的。在底层,生成器对象支持迭代器协议(protocol),并且做的事情大致类似于 Counter 类。
David Mertz 的文章,Iterators and Simple Generators ,很好的介绍。
关于python - 如何构建一个基本的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19151/