迭代器实现:
class Fib(object):
def __init__(self, stop):
self.stop = stop
self.current = 0
self.num1 = self.num2 = 1
def __iter__(self):
return self
def __next__(self):
x = self.num1
if self.current < self.stop:
self.current += 1
self.num1, self.num2 = self.num2, self.num1 + self.num2
return x
raise StopIteration
生成器实现:
def Fib(stop):
current = 0
num1 = num2 = 1
while current < stop:
yield num1
num1, num2 = num2, num1 + num2
current += 1
来源:51CTO
作者:wx5a4c600866558
链接:https://blog.51cto.com/13560219/2482320