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
继续阅读与本文标签相同的文章
-
打通“最后一公里”送药地图 访海派医药集团总经理张翔
2026-05-18栏目: 教程
-
上海首个保税展示展销场所亮相 海外商品“全球同质同价”
2026-05-18栏目: 教程
-
微信聊天记录导出excel使用方法分享卓师兄微信恢复大师
2026-05-18栏目: 教程
-
用好SmartArt,快速制作美观工整的PPT
2026-05-18栏目: 教程
-
CMU 15-721 15-查询执行和处理过程 Query Execution & Processing
2026-05-18栏目: 教程
