代码点读机 / Python / nonlocal

nonlocal Python · 关键字

在嵌套函数里声明要修改的是外层(但不是全局)的变量。

怎么用

nonlocal 变量名

小例子

def 外层():
    x = 1
    def 内层():
        nonlocal x
        x = 2
    内层()
    return x
print(外层())

运行结果

2

官方文档:https://docs.python.org/zh-cn/3/reference/simple_stmts.html#nonlocal

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条