嵌套函数中的python变量范围

前端之家收集整理的这篇文章主要介绍了嵌套函数中的python变量范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在阅读这个关于装饰的 article.

在步骤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,因为它根本没有被调用

解决方法

你不是在呼唤内心.你已经调用了outer,它返回内部,但没有调用它.如果你想调用inner,请执行foo()(因为你将outer()的结果赋予名称foo).

您引用的段落与此问题相关.你说你已经明白为什么内在得到x的值,这就是那个段落所解释的.基本上,如果在嵌套函数中使用局部变量,并且返回嵌套函数,则变量的值与返回的函数一起存储,即使该变量的定义范围不再处于活动状态.通常x在外部完成后会消失,因为x只是外部的局部.但外部返回内部,仍然需要访问x.所以x被包含在所谓的闭包中,所以稍后它仍然可以被内部访问.

原文链接:https://www.f2er.com/python/186023.html

猜你在找的Python相关文章