问题:在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行为差异的信息。
回答 0
g.next()已重命名为g.__next__()。这样做的原因是一致性:特殊方法(例如__init__()和)__del__()都带有双下划线(在当前情况下为“ dunder”),并且.next()是该规则的少数exceptions之一。这已在Python 3.0中修复。[*]
但是请不要g.__next__()使用next(g)。
[*]还有其他特殊属性可以解决此问题;func_name,现在__name__,等等。
回答 1
回答 2
如果您的代码必须在Python2和Python3下运行,请使用2to3 六个库,如下所示:
import six
six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

