如何构建一个基本的迭代器? [英] How to build a basic iterator?
问题描述
如何在 python 中创建迭代函数(或迭代器对象)?
How would one create an iterative function (or iterator object) in python?
推荐答案
python 中的迭代器对象符合迭代器协议,这基本上意味着它们提供了两种方法:__iter__()
和 __next__()
.
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__()
and __next__()
.
__iter__
返回迭代器对象并被隐式调用在循环开始处.
The
__iter__
returns the iterator object and is implicitly called at the start of loops.
__next__()
方法返回下一个值,并在每次循环增量时隐式调用.当没有更多值要返回时,此方法会引发 StopIteration 异常,循环构造隐式捕获该异常以停止迭代.
The __next__()
method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.
这是一个简单的计数器示例:
Here's a simple example of a counter:
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
使用生成器更容易编写,如上一个答案所述:
This is easier to write using a generator, as covered in a previous answer:
def counter(low, high):
current = low
while current < high:
yield current
current += 1
for c in counter(3, 9):
print(c)
打印的输出将是相同的.在引擎盖下,生成器对象支持迭代器协议并执行与类 Counter 大致相似的操作.
The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.
David Mertz 的文章 Iterators and Simple Generators 非常不错介绍.
David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.
这篇关于如何构建一个基本的迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!