斐波那契数列:后一个数为前两个数的和。由于要不断交换数字,要用的python的数字交换。
a = 2 b = 5 print(b) a, b = b, a + b print(b) a, b = b, a + b print(b)
用迭代器来做。
class Test: def __init__(self, a, b): self.a = a self.b = b def __iter__(self): return self def __next__(self): if self.b > 20: raise StopIteration self.a, self.b = self.b, self.a + self.b return self.b test = Test(0, 1) for i in test: # for 循环就是在执行__next__ print(i)
如果用生成器yield来做会简单很多。
def shulie(a, b, max): while b < max: a, b = b, a + b yield b # yield执行一次会退出并挂起。下次从挂起的地方继续 for i in shulie(0, 1, 20): # for 循环就是在执行__next__ print(i)
python基础-面向对象(十八)面向对象进阶(六)迭代器协议实现斐波那契数列
原文:https://www.cnblogs.com/liaoyifu/p/14137834.html