Python内部变量与外部变量
def outer():
x = 'outer x'
def inner():
x = 'inner x'
print(x)
inner()
print(x) # 这里的`x`与`x = 'outer x'`处在同一个Enclosing
outer()
运行结果:
inner x
outer x
使用nonlocal
def outer():
x = 'outer x'
def inner():
nonlocal x
x = 'inner x'
print(x)
inner()
print(x)
outer()