第一次遇到nonlocal关键字时有点不解,查阅了很多文章,大多都写的不明不白的。弄懂之后在这里做一个知识点整理,相信大家看完下文内容后就可以很好地理解nonlocal的用法。
- 首先来看比较官方的解释
当在 Python 中使用嵌套函数时,内层函数可以访问外层函数的变量。然而,如果想要修改外层函数的变量,就需要使用 nonlocal 关键字。否则,Python 会认为这是一种在内层函数中创建新变量的方式,而不是修改外层函数的变量。因此,如果想要修改外层函数的变量,就需要在内层函数中使用 nonlocal 关键字来声明这个变量是外层函数中的变量。
总结来说,就是nonlocal可以让内层函数直接访问并修改外层函数的变量。用几个简单的例子帮助大家理解:
-
- 如果在内层函数创建一个与外层函数变量同名的变量x,那么内层函数变量会直接对外层变量的值进行覆盖
def outer():
x = 0 # 外层函数变量 x
def inner1():
x = 7
x += 1 # 修改外层函数变量 x,但没有使用 nonlocal
print("inner1:", x)
inner1()
print("outer:", x)
outer()
#inner1: 8
#outer: 0
-
- 如果在内层函数中直接对外层函数变量进行访问,那么就会直接读取外层函数变量值
def outer_func():
x = 0
def inner_func():
print("inner x:", x)
inner_func()
print("outer x:", x)
outer_func()
#inner x: 0
#outer x: 0
-
- 如果在内层函数中对外层函数变量进行修改,那么程序报错
def outer_func():
x = 0
def inner_func():
x += 1
print("inner x:", x)
inner_func()
print("outer x:", x)
outer_func()
#UnboundLocalError: local variable 'x' referenced before assignment
-
- 使用nonlocal关键字,声明此变量为外层函数中的变量
def outer():
x = 0 # 外层函数变量 x
def inner2():
nonlocal x # 声明 x 为外层函数变量
x += 7 # 修改外层函数变量 x
print("inner2:", x)
inner2()
print("outer:", x)
outer()
#inner2: 7
#outer: 7
总而言之,如果希望在内层函数中使用并修改外层函数变量,那就需要使用nonlocal。