比较一下,不使用
nonlocal:
x = 0def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x)outer()print("global:", x)# inner: 2# outer: 1# global: 0对此,使用
nonlocal,其中
inner()的
x是现在还
outer()的
x:
x = 0def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x)outer()print("global:", x)# inner: 2# outer: 2# global: 0如果要使用global,它将绑定x到正确的“全局”值:
x = 0def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x)outer()print("global:", x)# inner: 2# outer: 1# global: 2


