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

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

本文介绍了嵌套函数中的python变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这篇关于装饰者。



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

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

如果我们运行它:

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

它不打印x。根据解释:

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



我明白inner()会得到x的值,但为什么它不会打印出来?

感谢

更新



感谢所有的答案。现在我明白了原因。
return inner 仅仅是一个指向inner()的指针完全没有被调用

解决方案

你不是调用 inner 。您已经调用 outer ,它会返回 inner ,但不调用它。如果你想调用 inner ,执行 foo()(因为你把 ()到名称 foo )。



您引用的段落是排序这个问题的切线。你说你已经理解为什么 inner 得到 x 的值,这就是段落解释的内容。基本上,如果在嵌套函数中使用局部变量,并且返回嵌套函数,则即使该变量定义的作用域不再处于活动状态,变量的值也会与返回的函数一起存储。通常 x 会在 outer 完成后消失,因为 x 对 outer 来说只是本地的。但 outer 返回 inner ,仍然需要访问 x 。因此 x 会被封装到所谓的闭包中,因此稍后仍可以通过 inner 访问。


I am reading this article about decorator.

At Step 8 , there is a function defined as:

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

and if we run it by:

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

it doesn't print x. According to the explanation :

However, I don't really understand what the second paragraph means.

I understand inner() does get the value of x but why it doesn't print x out?

thanks

UPDATE:

Thanks all for the answers. Now I understand the reason.the "return inner" is just a pointer to inner() but it doesn't get executed, that is why inner() doesn't print x as it is not called at all

解决方案

You are not calling inner. You have called outer, which returns inner, but without calling it. If you want to call inner, do foo() (since you assinged the result of outer() to the name foo).

The paragraph you quoted is sort of tangential to this issue. You say you already understand why inner gets the value of x, which is what that paragraph is explaining. Basically, if a local variable is used in a nested function, and that nested function is returned, the value of the variable is stored along with the returned function, even if the scope where that variable was defined in no longer active. Normally x would be gone after outer finished, because x is just local to outer. But outer returns inner, which still needs access to x. So x gets wrapped up into what's called a closure, so it can still be accessed by inner later on.

这篇关于嵌套函数中的python变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:46