# 类实现
class fib:
def __init__(self, n):
self.current = 0
self.n = n
self.num1, self.num2 = 0, 1
def __iter__(self):
return self
def __next__(self):
if self.current < self.n:
num = self.num2
self.num1, self.num2 = self.num2, self.num1 + self.num2
self.current += 1
return num
raise StopIteration
aa = fib(340)
for i in aa:
print(i)
# 生成器实现
def fib(n):
current = 0
num1, num2 = 0, 1
while current < n:
num = num2
num1, num2 = num2, num1 + num2
current += 1
yield num
raise StopIteration
a = fib(5)
for i in a:
print(i)
网友评论