global是在函数内部声明变量为全局变量
nonlocal是声明该变量不是当前函数的本地变量
看如下例子:
x=300
def test1():
x =200
def test2():
#global x
nonlocal x
print(x)
x=100
print(x)
return test2
t1 = test1()
t1()
结果为:
200
100
x=300
def test1():
x =200
def test2():
global x
# nonlocal x
print(x)
x=100
print(x)
return test2
t1 = test1()
t1()
结果为:
300
100