class Next: def __init__(self, wrapped): self.wrapped = wrapped self.offset = 0 def __iter__(self): return self def __next__(self): # 返回下一个元素 if self.offset >= len(self.wrapped): raise (StopIteration) else: item = self.wrapped[self.offset] self.offset += 1 return item # 返回指定索引位置处的元素 if self.offset >= len(self.wrapped): raise (StopIteration)这段代码场景
_iter__
方法返回 self
,表明这个类的实例本身就是一个迭代器__next__
方法检查 offset
是否已经超出了 wrapped
序列的长度。如果超出了,说明没有更多的元素可以返回,此时抛出 StopIteration
异常print(next(I)) # 输出 11 print(next(I)) # 输出 22 print(next(I)) # 输出 33 print(next(I)) # 输出 44 print(next(I)) # 输出 55 print(next(I)) # 抛出 StopIteration 异常
for
循环感受不到异常被触发,自动处理 StopIteration
异常,StopIteration
异常被抛出捕获终止循环
# 定义一个列表 x = [1, 2, 3] # 获取迭代器 it = iter(x) # 手动模拟 for 循环的行为 while True: try: # 获取下一个元素 item = next(it) print(item) except StopIteration: # 捕获 StopIteration 异常,终止循环 break