1 class Fib(object): 2 3 def __init__(self): 4 self.a,self.b=0,1 5 6 def __iter__(self): 7 return self 8 9 def __next__(self): 10 self.a,self.b=self.b,self.a+self.b 11 if self.a > 100: 12 raise StopIteration() 13 return self.a
运行
for n in Fib(): print(n)
结果
1 1 2 3 5 8 13 21 34 55 89