x = 0
def outer():
x = 1
def inner():
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
结果是:
inner: 2
outer: 1
global: 0
global
适用于函数内部修改全局变量的值
x = 0
def 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
nonlocal
适用于嵌套函数中内部函数修改外部变量的值
x = 0
def 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
如果没有使用以上关键字,对全局变量或者外部变量进行修改,python会默认将全局变量隐藏起来