今天爱分享给大家带来Python构造一个基本的Python迭代器【面试题详解】,希望能够帮助到大家。
python中的迭代器对象遵守迭代器协议,也就意味着python会提供两个方法:iter() 和 next().方法__iter__ 返回迭代器对象并且在循环开始时隐含调用.方法next()返回下一个值并且在每次循环中隐含调用.方法next()在没有任何值可返回时,抛出StopIteration异常.之后被循环构造器捕捉到而停止迭代.
下面是简单的计数器例子:
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self): # Python 3: def __next__(self)
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
for c in Counter(3, 8):
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, 8):
print c
输出是一样的.本质上说,生成器对象支持迭代协议并且大致完成和计数器类相同的事情.
原文链接:https://blog.itblood.com/4470.html,转载请注明出处。

![训练杀手v92.0 AI版[PC+安卓/741M/更新]Training Slayer [v92.0] [同人SLG/汉化/动态]](/wp-content/uploads/replace/2025/10/05/11adbd11a0bf07c72052028ffffd6222.webp)