我想知道是否有可能在Python中使用閉包來處理其名稱空間中的變量。您可能會稱這種副作用是因爲狀態正在關閉本身之外進行更改。我想這樣做Python關閉副作用
def closureMaker():
x = 0
def closure():
x+=1
print x
return closure
a = closureMaker()
a()
1
a()
2
顯然是我希望做的是比較複雜的,但這個例子說明了什麼我談論。
我想知道是否有可能在Python中使用閉包來處理其名稱空間中的變量。您可能會稱這種副作用是因爲狀態正在關閉本身之外進行更改。我想這樣做Python關閉副作用
def closureMaker():
x = 0
def closure():
x+=1
print x
return closure
a = closureMaker()
a()
1
a()
2
顯然是我希望做的是比較複雜的,但這個例子說明了什麼我談論。
你不能在Python 2.x中完全做到這一點,但你可以使用一個技巧來獲得相同的效果:使用一個可變對象,如列表。
def closureMaker():
x = [0]
def closure():
x[0] += 1
print x[0]
return closure
您還可以使x具有命名屬性或字典的對象。這可以比列表更具可讀性,特別是如果你有多個這樣的變量需要修改。
在Python 3.x中,您只需要將nonlocal x
添加到您的內部函數中。這導致x
的分配轉到外部範圍。
請解釋原因?我試圖在python文檔中找到這方面的信息。 –
@André:PEP 3104提供信息,如果技術性的話:http://www.python.org/dev/peps/pep-3104/ –
對我而言,它似乎應該**都可以工作。我只讀[this](http://docs.python.org/reference/executionmodel.html#naming-and-binding):*「如果定義發生在功能塊中,則範圍擴展到包含在定義一個,除非包含的塊爲該名稱引入了不同的綁定。「* –
What limitations have closures in Python compared to language X closures?
nonlocal keyword in Python 2.x
例子:
def closureMaker():
x = 0
def closure():
nonlocal x
x += 1
print(x)
return closure
我會記住這爲其他問題的副本,除了其他問題確實應該標明這一個的副本;這個問題很簡單,寫得很好,寫得很好。但也見http://stackoverflow.com/questions/141642/what-limitations-have-closures-in-python-compared-to-language-x-closures – ninjagecko
因此,沒有辦法合併兩個或更多的問題? ; p –