global 将局部变量和全局变量进行连接,即修改了局部变量的值,全局变量的值也会随之改变,但中间层局部作用域的变量不受影响;
nonlocal 是将局部变量和其上一层的变量进行连接,即修改了该局部变量的值,其上一层的变量的值也会随之改变,但其他中间层局部作用域以及全局的变量不受影响。
可通过下面示例进行区分:
s = 0
def fun():
s = 1
def fun1():
s = 2
def fun2():
# nonlocal s
global s
s = 0
for i in range(100):
s += i
fun2()
print('fun1: ', s)
fun1()
print('fun: ', s)
fun()
print('global: ', s)
----------------
fun1: 2
fun: 1
global: 4950
----------------------------> 分界线 <-------------------------
s = 0
def fun():
s = 1
def fun1():
s = 2
def fun2():
nonlocal s
# global s
s = 0
for i in range(100):
s += i
fun2()
print('fun1: ', s)
fun1()
print('fun: ', s)
fun()
print('global: ', s)
----------------
fun1: 4950
fun: 1
global: 0