Python进阶-----类中的迭代器协议

回顾什么是迭代器协议:
  迭代器协议:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个
StopIteration异常,以终止迭代(只能往后走,不能往前退)
类中的可迭代对象必须提供__iter__()和__next__()方法

 1 class Foo:
 2     def __init__(self,n):
 3         self.n = n
 4 
 5     def __iter__(self):
 6         return self
 7 
 8     def __next__(self):
 9         if self.n ==5:
10             raise StopIteration('结束了')
11         self.n += 1
12         return self.n
13 
14 f = Foo(1)
15 for i in f:
16     print(i)
17 
18 # 采用for循环碰到stopiteration自动停止,而不会影响真个程序
19 
20 print(f.__next__())   #使用next(f)或者f.__next__()会抛出异常,程序终止

 例子:使用迭代器协议生成斐波那契数列

 1 class Fib:
 2     def __init__(self):
 3         self._a = 1
 4         self._b = 1
 5     def __iter__(self):
 6         return self
 7     def __next__(self):
 8         if self._a > 100:
 9             raise StopIteration('终止了')
10         self._a,self._b = self._b,self._a+self._b
11         return self._a
12 
13 f = Fib()
14 for i in f:
15     print(i)
原文地址:https://www.cnblogs.com/Meanwey/p/9889276.html