1、迭代器基于下面两个个方法:
(1)__next__ 返回容器的下一个项目
(2)__iter__ 返回迭代器本身
2、当序列遍历完时,将抛出StopIteration异常,所以通过捕获这个异常来停止循环
下面是自定义迭代器的示例代码:
#encoding:UTF-8 class MyIterator(object): def __init__(self,step): self.step=step def __next__(self): if self.step==0: raise StopIteration self.step-=1 return self.step def __iter__(self): return self for i in MyIterator(6): print(i)输出结果:
>>> ================================ RESTART ================================ >>> 5 4 3 2 1 0 >>>