4 回答

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊

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

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