nonlocal Python · 关键字
在嵌套函数里,修改外层函数的变量(不是全局也不是本地),需要声明 nonlocal。像你在里屋跟智能管家说想调外屋的灯开关,得说明“我要动外面那盏灯”。
怎么用
nonlocal x # 声明我要修改外层函数的 x
小例子
def outer():
x = 5 # 外层函数的局部变量
def inner():
nonlocal x # 声明我要修改外层函数的 x
x = 10
inner()
return x
print(outer()) # 10
不加nonlocal的对比
def outer():
x = 5
def inner():
x = 10 # 这创建了一个新的局部变量,不影响外层的 x
inner()
return x
print(outer()) # 5
官方文档:https://docs.python.org/zh-cn/3/reference/simple_stmts.html#nonlocal
在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条