慕的地8271018
比较这个,不使用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