簡體   English   中英

generator.next() 在 Python 3 中可見嗎?

[英]Is generator.next() visible in Python 3?

我有一個生成系列的生成器,例如:

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 行為差異的內容。

g.next()已重命名為g.__next__() 這樣做的原因是一致性:像__init__()__del__()這樣的特殊方法都有雙下划線(或當前白話中的“dunder”),而.next()是該規則的少數例外之一。 這已在 Python 3.0 中修復。 [*]

但是不要調用g.__next__() ,而是使用next(g)

[*] 還有其他特殊屬性已得到此修復; func_name ,現在是__name__ 等。

嘗試:

next(g)

查看這個簡潔的表格,其中顯示了 2 和 3 之間的語法差異。

如果您的代碼必須在 Python2 和 Python3 下運行,請使用 2to3庫,如下所示:

import six

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM