使用迭代器实现斐波那契数列
1 class Finacci(object): 2 def __init__(self,num): 3 self.num = num 4 self.a = 1 5 self.b = 1 6 self.current_index=0 7 def __iter__(self): #定义迭代器 8 return self 9 def __next__(self): 10 if self.current_index<self.num: 11 data = self.a 12 13 self.a,self.b=self.b,self.a+self.b 14 self.current_index+=1 15 return data 16 else: 17 raise StopIteration 18 19 if __name__ == '__main__': 20 fib = Finacci(5) 21 # val = next(fib) 22 for value in fib: 23 print(value)