您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

嵌套函数中的python变量范围

5b51 2022/1/14 8:22:56 python 字数 2224 阅读 569 来源 www.jb51.cc/python

我正在阅读这个关于装饰的 article. 在步骤8,有一个定义为: def outer(): x = 1 def inner(): print x # 1 return inner 如果我们运行它: >>> foo = outer() >>> foo.func_closure # doctest: +ELLIPSIS 它不打印x.根据解释: Everythi

概述

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

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

总结

以上是编程之家为你收集整理的嵌套函数中的python变量范围全部内容,希望文章能够帮你解决嵌套函数中的python变量范围所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶