嵌套函数中的python变量作用域

2024-05-12 06:03:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读这篇关于decorator的文章。

在步骤8中,有一个函数定义为:

def outer():
    x = 1
    def inner():
       print x # 1
    return inner

如果我们运行它:

>>> foo = outer()
>>> foo.func_closure # doctest: +ELLIPSIS

它不打印x。根据解释:

Everything works according to Python’s scoping rules - x is a local variable in our function outer. When inner prints x at point #1 Python looks for a local variable to inner and not finding it looks in the enclosing scope which is the function outer, finding it there.

But what about things from the point of view of variable lifetime? Our variable x is local to the function outer which means it only exists while the function outer is running. We aren’t able to call inner till after the return of outer so according to our model of how Python works, x shouldn’t exist anymore by the time we call inner and perhaps a runtime error of some kind should occur.

然而,我真的不明白第二段的意思。

我知道inner()确实得到x的值,但为什么它不输出x?

谢谢

更新

谢谢大家的回答。现在我明白了原因。 “return inner”只是一个指向inner()的指针,但它没有被执行,这就是inner()没有打印x的原因,因为它根本没有被调用


Tags: ofthetoreturnfooislocaldef