nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。
>>> def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
>>> outer()
inner: 2
outer: 2
Python2.x解决函数引用外层变量的方法只有使用global 关键字定义全局变量,另一种可行的解决方案是使用列表或字典代替要操作的关键字
>>> def outer():
x = [1]
def inner():
x[0] += 1 #修改x[0]保存的值
print("inner:", x[0])
inner()
print("outer:", x[0])
>>> outer()
inner: 2
outer: 2