Skip to main content
 首页 » 编程设计

python之为什么 Z 没有闭包

2025年05月04日16lyhabc

1.)为什么没有为示例 1 生成闭包而 例如 2 有闭包。

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> 

请您参考如下方法:

Why the closure is not generated for example 1 whereas for example 2 there is closure.

因为内部函数不需要外部函数的z。

Even though there is no closure for Z how I am able to get the value from outer function for Z

你不能。您得到的 z 是您传递的参数,而不是来自外部函数的 z。 (这就是为什么它是 2 而不是 0。)