开发者

variable scope in python nested functions

开发者 https://www.devze.com 2023-01-19 19:42 出处:网络
As I am studying decorators, I noticed something strange : def f(): ...msg=\'aa\' ..开发者_C百科.def a():

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

精彩评论

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