1 class Foo:
 2     def __init__(self,n):
 3         self.n=n
 4     def __iter__(self):
 5         return self
 6 
 7     def __next__(self):
 8         if self.n == 13:
 9             raise StopIteration('终止了')
10         self.n+=1
11         return self.n
12 
13 f1=Foo(10)
14 
15 for i in f1:  # obj=iter(f1)------------>f1.__iter__()
16      print(i)  #obj.__next__()

输出

11
12
13

 

  迭代器协议实现斐波那契数列

 

 1 class Fib:
 2     def __init__(self):
 3         self._a=1
 4         self._b=1
 5 
 6     def __iter__(self):
 7         return self
 8     def __next__(self):
 9         if self._a > 100:
10             raise StopIteration('终止了')
11         self._a,self._b=self._b,self._a + self._b
12         return self._a
13 
14 f1=Fib()
15 print(next(f1))
16 print(next(f1))
17 print(next(f1))
18 print(next(f1))
19 print(next(f1))
20 print('==================================')
21 for i in f1:
22     print(i)

输出

1
2
3
5
8
==================================
13
21
34
55
89
144

收藏 打印