查看: 1639|回复: 0

python 3.x 错误 ‘generator’ object has no attribute ‘next’

[复制链接]

665

主题

1234

帖子

6575

积分

xdtech

Rank: 5Rank: 5

积分
6575
发表于 2019-5-1 13:28:06 | 显示全部楼层 |阅读模式

用python生成斐波那契數列

def fab(max):  n,a,b=0,0,1  while n<max:    yield b    a,b=b,a+b    n=n+1for 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__()


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表