在Python 3中generator.next()可见吗?
我有一个生成器,它可以生成一系列的东西,比如:
def triangle_nums():
'''Generates a series of triangle numbers'''
tn = 0
counter = 1
while True:
tn += counter
yield tn
counter += + 1
在Python 2中,我可以这样调用:
g = triangle_nums() # get the generator
g.next() # get the next value
但是在Python 3中,如果我执行同样的两行代码,就会出现以下错误:
AttributeError: 'generator' object has no attribute 'next'
不过,在Python 3中,循环迭代器的语法是可以用的。
for n in triangle_nums():
if not exit_cond:
do_something()...
我还没有找到任何能解释Python 3中这种行为差异的资料。
3 个回答
12
如果你的代码需要在Python2和Python3两个版本下都能运行,可以使用一个叫做2to3的工具,配合一个名为six的库,像这样使用:
import six
six.next(g) # on PY2K: 'g.next()' and onPY3K: 'next(g)'
157