4 回答

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
Python沒有變量聲明,因此必須弄清楚變量本身的范圍。它通過一個(gè)簡(jiǎn)單的規(guī)則來實(shí)現(xiàn):如果對(duì)函數(shù)內(nèi)部的變量賦值,則該變量被視為本地變量。[1] 因此,這條線
counter += 1
隱含地使counter
本地化increment()
。但是,嘗試執(zhí)行此行將嘗試counter
在分配之前讀取局部變量的值,從而產(chǎn)生一個(gè)UnboundLocalError
。[2]
如果counter
是全局變量,global
關(guān)鍵字將有所幫助。如果increment()
是本地函數(shù)和counter
局部變量,則可以nonlocal
在Python 3.x中使用。

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
您需要使用全局語句,以便修改全局變量計(jì)數(shù)器,而不是局部變量:
counter = 0def increment(): global counter counter += 1increment()
如果counter
定義的封閉范圍不是全局范圍,則在Python 3.x上可以使用非本地語句。在Python 2.x的相同情況下,您將無法重新分配到非本地名稱counter
,因此您需要進(jìn)行counter
可變并修改它:
counter = [0]def increment(): counter[0] += 1increment()print counter[0] # prints '1'

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
要回答主題中的問題,*是,Python中有閉包,除了它們只適用于函數(shù)內(nèi)部,并且(在Python 2.x中)它們是只讀的; 您無法將名稱重新綁定到其他對(duì)象(但如果該對(duì)象是可變的,則可以修改其內(nèi)容)。在Python 3.x中,您可以使用nonlocal
關(guān)鍵字來修改閉包變量。
def incrementer(): counter = 0 def increment(): nonlocal counter counter += 1 return counter return increment increment = incrementer()increment() # 1increment() # 2
*原始問題的標(biāo)題詢問了Python中的閉包。

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
您的代碼拋出的UnboundLocalError
原因已經(jīng)在其他答案中得到了很好的解釋。
但在我看來,你正試圖建立一些類似的東西itertools.count()
。
那你為什么不嘗試一下,看看它是否適合你的情況:
>>> from itertools import count>>> counter = count(0)>>> counter count(0)>>> next(counter)0>>> counter count(1)>>> next(counter)1>>> counter count(2)
添加回答
舉報(bào)