关键字nonlocal用来在函数或者其他作用域中使用外层(非全局变量)。换句话说,nonlocal用来声明变量不处于当前的函数当中,需要解释器在包含这个函数的函数中寻找nonlocal声明的同名变量,找到后就可以使用这个对象对应的值在当前函数中进行操作。
不使用nonlocal它用来在部分情况下代替global关键字,防止滥用。
def test():
x = 0
def inner():
x += 1
print(x)
inner()
print(x)
test()
运行会报以下错误:
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last)使用nonlocalin 7 print(x) 8 ----> 9 test() in test() 4 x += 1 5 print(x) ----> 6 inner() 7 print(x) 8 in inner() 2 x = 0 3 def inner(): ----> 4 x += 1 5 print(x) 6 inner() UnboundLocalError: local variable 'x' referenced before assignment
def test():
x = 0
def inner():
nonlocal x
x += 1
print(x)
inner()
print(x)
test()
正常运行,更改对内嵌函数外也依然有效。



