迭代器构造斐波那契数列

# class Fei(object):
# def __init__(self,n):
# self.n = n
# self.num1 = 0
# self.num2 = 1
# self.current = 0
#
# def __iter__(self):
# return self
#
# def __next__(self):
# if self.current < self.n:
# num = self.num1
# self.num1,self.num2 = self.num2,self.num1+self.num2
# self.current += 1
# return num
# else:
# raise StopIteration
#
# if __name__ == '__main__':
# fei = Fei(20)
# while True:
# try:
# print(next(fei),end=" ")
# except StopIteration:
# break

class Fei(object):
def __init__(self,n):
self.num1 = 0 # 第一个初始值
self.num2 = 1 # 第二个初始值
self.current = 0 # 代表下标,记录位置
self.n = n # 构造长度为n的斐波那契数列

def __iter__(self):
"""返回自身"""
return self

def __next__(self):
"""获取下一个位置元素"""
if self.current < self.n:
num = self.num1 # 用一个变量临时保存初始值0
self.num1,self.num2 = self.num2, self.num1+self.num2 # 构造斐波那契数列下一个值
self.current += 1 # 构造一次位置变更一次
return num
else:
raise StopIteration # 超出长度跑出停止迭代异常

if __name__ == '__main__':
fei = Fei(10)
for i in fei:
print(i,end=" ")

# def fei(n):
# num1,num2 = 0,1
# current = 0
# while current < n:
# num = num1
# num1,num2 = num2,num1+num2
# current += 1
# yield num
# else:
# raise StopIteration
#
# if __name__ == '__main__':
# f = fei(10)
# for i in f:
# print(i)

# print(list(f))


# while True:
# try:
# print(next(f),end=" ")
# except StopIteration:
# break

原文地址:https://www.cnblogs.com/daizhonglin/p/13453202.html