迭代器协议:__iter__和__next__

时间:2021-01-10 18:54:02
 1 class Foo:
 2     def __init__(self,x):
 3         self.x = x
 4     def __iter__(self):
 5         return self
 6     def __next__(self):
 7         if self.x == 15:
 8             raise StopIteration('数字过大')     #抛出异常
 9         self.x += 1
10         return self.x
11 
12 f1 = Foo(10)
13 print(f1.__next__())        #11
14 print(f1.__next__())        #12
15 print(f1.__next__())        #13
16 print(next(f1))             #14
17 print(next(f1))             #15
18 print(next(f1))             #StopIteration: 数字过大
19 for i in f1:
20     print(i)
21 # 11
22 # 12
23 # 13
24 # 14
25 # 15
26 
27 ## 迭代器实现斐波那契数列
28 class Foo:
29     def __init__(self):
30         self._a = 1
31         self._b = 1
32     def __iter__(self):
33         return self
34     def __next__(self):
35         if self._a > 100:
36             raise StopIteration('程序终止')
37         self._a,self._b = self._b,self._a + self._b
38         return self._a
39 f1 = Foo()
40 print(f1.__next__())
41 print(f1.__next__())
42 print(f1.__next__())
43 print(f1.__next__())
44 print(f1.__next__())
45 print(f1.__next__())
46 print('-------------')
47 for i in f1:            #for循环遍历f1是接着上面的内容继续,不会从头开始也不会往回返
48     print(i)