Python错误:AttributeError: 'generator' object has no attribute 'next'解决办法

版权声明:如需转载,请与我联系。WX:reborn0502 https://blog.csdn.net/gaifuxi9518/article/details/81059938

今天在学习生成器对象(generation object)运行以下代码时,遇到了一个错误:

#定义生成器函数
def liebiao():
	for x in range(10):
		yield x
#函数调用
g = liebiao()

#打印元素
print(g.next())
D:\>python test.py
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    print(g.next())
AttributeError: 'generator' object has no attribute 'next'

Google后发现,在python3.x版本中,python2.x的g.next()函数已经更名为g.__next__(),所以只需要将g.next()换成g.__next__()就可以了。如果你觉得g.__next__()太丑,使用next(g)也能达到相同效果。

这其实是版本更新所带来的无法避免的错误,毕竟python不像其他的编程语言,python2和python3之间互不兼容。

猜你喜欢

转载自blog.csdn.net/gaifuxi9518/article/details/81059938