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.
精彩评论