开发者

variable scope in python nested functions

As I am studying decorators, I noticed something strange :

def f():
...     msg='aa'
..开发者_C百科.     def a():
...             print msg
...     msg='bb'
...     def b():
...             print msg
...     return a,b
... 
>>> a,b = f()
>>> a()
bb
>>> b()
bb
>>> 

Why a() returns 'bb' and not 'aa' ??


Because a and b have the same outer scope, in which msg is bound to 'bb'. Put them in separate functions if you want them to have separate scopes.


Both a and b have read access to the outer scope (the local scope of f). As you overwrite the value of msg, the later call to a/b will read the new value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜