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'是本地的,而不是闭包或全局的。 –