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

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 :

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值