python 变量的作用域

变量作用域的LEGB原则

Local(function) Enclosing function locals Gobal(module) Built-in(Python)

E 的说明


In [2]: def f1():
   ...:     x = 100
   ...:     def f2():
   ...:         def f3():
   ...:             def f4():
   ...:                 print(x)
   ...:             f4()
   ...:         f3()
   ...:     f2()
   ...:

In [3]: f1()
100

python3 nonlocal变量

nonlocal 语句的主要作用是允许嵌套的作用域中的名称被修改,而不只是被引用.

程序角度是保存多个副本.


In [1]: def tester(start):
   ...:     state = start
   ...:     def nested(label):
   ...:         nonlocal state
   ...:         print(label, state)
   ...:         state += 1
   ...:     return nested
   ...:

In [2]: F = tester(0)

In [3]: F = tester(0)

In [4]: F('d')
d 0

In [5]: F('d')
d 1

In [6]: F('d')
d 2

In [7]: F('d')
d 3


注意问题

当执行一条nonlocal语句时,nonlocal名称一定在一个嵌套的def作用域中assigin过,否则则会报错

def tester(start):
    def nested(label):
        nonlocal state
        state = 0
        print(label, state)
    return nested

SyntaxError: no binding for nonlocal 'state' found

Loading Disqus comments...
Table of Contents