2009-07-02 18 views
149

我有一個生成一系列的發電機,例如:是否在python 3.0中可見generator.next()?

def triangleNums(): 
    '''generate series of triangle numbers''' 
    tn = 0 
    counter = 1 
    while(True): 
     tn = tn + counter 
     yield tn 
     counter = counter + 1 

在Python 2.6我能夠做出以下電話:在3.0

g = triangleNums() # get the generator 
g.next()   # get next val 

但是如果我執行相同的兩條線的代碼,我發現了以下錯誤:

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

但是,將循環迭代語法確實在3.0

工作10
for n in triangleNums(): 
    if not exitCond: 
     doSomething... 

我還沒有找到任何解釋這種3.0行爲差異的東西。

回答

232

正確,g.next()已更名爲g.__next__()。原因是有一致性。像__init__()__del__這樣的特殊方法都有雙下劃線(或者「dunder」,因爲它現在變得很流行,現在可以打電話了),而.next()是該規則的少數例外之一。 Python 3.0修復了這個問題。 [*]

但不是像保羅說的那樣呼叫g.__next__(),而是使用next(g)

[*]有更多的特殊屬性獲得此修復,如功能屬性。不再func_name,它現在__name__

80

嘗試:

next(g) 

退房this neat table顯示2和3之間的語法差異,當談到這一點。

+1

@MaikuMori我固定的聯繫(等待同伴修訂) (該網站http://diveintopython3.org似乎已關閉,鏡像網站http://diveintopython3.ep.io仍然存在) – gecco 2012-01-05 20:59:34

+1

再次修復該鏈接。 http://python3porting.com/differences.html更完整,順便說一句。 – 2013-07-27 03:53:41

+0

鏈接仍然被破壞... – Klik 2017-10-21 01:16:35

7

如果你的代碼必須Python2和Python3下運行,使用2to3的six庫這樣的:

import six 

six.next(g) # on PY2K: 'g.next()' and onPY3K: 'next(g)' 
相關問題