class Fib: def __init__(self): self.a=1 #定义启示的两个值 self.b=1 def __iter__(self): #设置迭代器协议 return self def __next__(self): if self.a>100: raise StopIteration self.a,self.b=self.b,self.a+self.b #实现斐波那契数列 #a,b=b,a# 快速交换2个值 return self.a f1=Fib() print(next(f1)) print(next(f1)) print(next(f1)) print(next(f1)) print("++++++++++++++++++++++") for i in f1:#注意next是不能往回走的 print(i)
》》》》
1
2
3
5
++++++++++++++++++++++
8
13
21
34
55
89
144