1
1.)爲什麼封閉不生成例1,而 例如2有封閉。爲什麼沒有關閉Z
2.)示例1即使沒有Z的閉包,我如何能夠從Z的外層函數中獲取值(因爲一旦局部函數範圍結束,所有對象都將基於閉包進行垃圾收集或保留)
實施例1
def outer():
x=3
y=4
z=0
def inner(z):
return x,y,z
return inner
i=outer()
i.__closure__
Out[69]:
(<cell at 0x000000000451D738: int object at 0x0000000001D681A8>,
<cell at 0x000000000451D408: int object at 0x0000000001D68190>)
輸出
i(2)
Out[78]: (3, 4, 2)
但是,當我做
實施例2
def outer():
x=3
y=4
z=0
def inner():
return x,y,z
return inner
i=outer()
i.__closure__
Out[72]:
(<cell at 0x000000000451D528: int object at 0x0000000001D681A8>,
<cell at 0x000000000451D3A8: int object at 0x0000000001D68190>,
<cell at 0x000000000451D9A8: int object at 0x0000000001D681F0>
在例1中,你用同名的參數映射了非本地'z'。 – chepner
將你的參數調用到'內部',而不是像'w'那樣影響'z'。在這種情況下,你希望第三個輸出參數是'z'還是'w'?無論哪種方式,它將作爲編碼工作。不知道是什麼讓你失望。 –
函數參數也是本地人; 'def inner(z):'中的'z'是本地的,而不是閉包或全局的。 –