问题:在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行为差异的信息。

I have a generator that generates a series, for example:

def triangle_nums():
    '''Generates a series of triangle numbers'''
    tn = 0
    counter = 1
    while True:
        tn += counter
        yield tn
        counter += + 1

In Python 2 I am able to make the following calls:

g = triangle_nums()  # get the generator
g.next()             # get the next value

however in Python 3 if I execute the same two lines of code I get the following error:

AttributeError: 'generator' object has no attribute 'next'

but, the loop iterator syntax does work in Python 3

for n in triangle_nums():
    if not exit_cond:
       do_something()...

I haven’t been able to find anything yet that explains this difference in behavior for Python 3.


回答 0

g.next()已重命名为g.__next__()。这样做的原因是一致性:特殊方法(例如__init__()和)__del__()都带有双下划线(在当前情况下为“ dunder”),并且.next()是该规则的少数exceptions之一。这已在Python 3.0中修复。[*]

但是请不要g.__next__()使用next(g)

[*]还有其他特殊属性可以解决此问题;func_name,现在__name__等等。

g.next() has been renamed to g.__next__(). The reason for this is consistency: special methods like __init__() and __del__() all have double underscores (or “dunder” in the current vernacular), and .next() was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]

But instead of calling g.__next__(), use next(g).

[*] There are other special attributes that have gotten this fix; func_name, is now __name__, etc.


回答 1

尝试:

next(g)

查看这个整洁的表,其中显示了2和3之间的语法差异。

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.


回答 2

如果您的代码必须在Python2和Python3下运行,请使用2to3 六个库,如下所示:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

If your code must run under Python2 and Python3, use the 2to3 six library like this:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。