nonlocal
和global
的不同,nolocal
改变的是上级作用域中的变量,global
改变的是全局作用域中的变量。
global
name = 'shaolei'
def outer():
name = 'zhangsan'
def inner():
global name
name = 'lisi'
inner()
print(name)
outer()
输出结果是:
zhangsan
nonlocal
:
name = 'shaolei'
def outer():
name = 'zhangsan'
def inner():
nonlocal name
name = 'lisi'
inner()
print(name)
outer()
输出结果是:
lisi