class fibonacci(object):
def __init__(self, num):
# 记录生成fibonacci数列的个数
self.num = num
# 记录数列的前2个值
self.a = 0
self.b = 1
# 记录当前生成数列的索引
self.current_index = 0
def __iter__(self):
return self
def __next__(self):
if self.current_index < self.num:
result = self.a
self.a, self.b = self.b, self.a + self.b
self.current_index += 1
return result
else:
raise StopIteration
# 创建迭代器
f = fibonacci(5)
for value in f:
print(value)
迭代器完成fibonacci数列
最新推荐文章于 2023-04-28 12:20:32 发布