迭代器协议

 1 class Foo:
 2     '迭代器协议:对象可以调用next()方法,且当不可迭代的时候会产生stopiteration,且只能向后,不能向前。'
 3     a = 10
 4 
 5     def __iter__(self):  # 根据迭代器协议定义一个__iter__()方法
 6         return self
 7 
 8     def __next__(self):  # 根据迭代器协议定义一个next()方法
 9         if self.a <=13:
10             self.a += 1
11             return self.a
12         raise StopIteration('终止程序')
13 
14 f1 = Foo()
15 print(f1.__next__())  # 调用next()方法
16 print(f1.__next__())
17 # print(next(f1))
18 # print(next(f1))
19 # print(next(f1))
20 # print(next(f1))
21 for i in f1:  # 实际是先调用了f1.__iter__()------->iter(f1) 变为可迭代对象 然后调用next()方法
22     print(i)
23 输出:
24 11
25 12
26 13
27 14

 

posted @ 2020-03-09 15:47  竹石2020  阅读(81)  评论(0编辑  收藏  举报