加入收藏 | 设为首页 | 会员中心 | 我要投稿 大庆站长网 (https://www.0459zz.com/)- 科技、智能边缘云、事件网格、云计算、站长网!
当前位置: 首页 > 编程开发 > Python > 正文

嵌套函数中的python变量范围

发布时间:2020-12-15 13:21:59 所属栏目:Python 来源:互联网
导读:我正在阅读这个关于装饰的 article. 在步骤8,有一个定义为: def outer(): x = 1 def inner(): print x # 1 return inner 如果我们运行它: foo = outer() foo.func_closure # doctest: +ELLIPSIS 它不打印x.根据解释: Everythi

我正在阅读这个关于装饰的 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被包含在所谓的闭包中,所以稍后它仍然可以被内部访问.

(编辑:大庆站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读