温馨提示×

python中nonlocal的用法是什么

小亿
185
2023-12-14 18:20:20
栏目: 编程语言

nonlocal关键字用于在嵌套函数中修改外层(非全局)变量。

在Python中,当在嵌套函数中想要修改外层函数的局部变量时,通常会使用nonlocal关键字。nonlocal关键字用于声明变量为非全局变量,以便在嵌套函数中修改外层函数的局部变量。

下面是nonlocal关键字的用法示例:

def outer_func():
    x = 10

    def inner_func():
        nonlocal x
        x = 20

    inner_func()
    print(x)  # 输出结果为 20

outer_func()

在上面的示例中,内层函数inner_func()使用nonlocal关键字声明变量x为非全局变量,并将其值修改为20。然后在外层函数outer_func()中,调用inner_func()并打印变量x的值。由于使用了nonlocal关键字,内层函数修改了外层函数的局部变量x的值,因此输出结果为20。

0