用Python生成斐波那契數列
def fab(max):
n,a,b=0,0,1
while n<max:
yield b
a,b=b,a+b
n=n+1
for n in fab(5):
print(n)
运行正常 当运行下面的方式时 f=fab(5) f.next() 出现下面的错误 Traceback (most recent call last): File “<pyshell#32>”, line 1, in <module> f.next() AttributeError: ‘generator’ object has no attribute ‘next’
原因是在python 3.x中 generator(有yield关键字的函数则会被识别为generator函数)中的next变为__next__了,next是python 3.x以前版本中的方法
修改为下面这样运行正常 f=fab(5) f.__next__()