温馨提示×

python中的nonlocal怎么使用

小亿
84
2024-04-26 16:47:42
栏目: 编程语言

nonlocal关键字用于在一个嵌套的函数中对上一级函数中的变量进行赋值操作。使用nonlocal关键字可以让函数内部的变量指向上一级函数的变量,而不是创建一个新的局部变量。

下面是一个使用nonlocal关键字的示例:

def outer_function():
    x = 10
    
    def inner_function():
        nonlocal x
        x = 20
        print("Inner function: ", x)
    
    inner_function()
    print("Outer function: ", x)

outer_function()

在这个示例中,inner_function中使用nonlocal关键字指定了x变量为上一级函数outer_function中的x变量,所以在inner_function中对x的赋值操作会影响到outer_function中的x变量。运行这段代码会输出:

Inner function:  20
Outer function:  20

0