内部函数访问外部函数的(可变、不可变)变量

在 Python 中,内部函数可以访问外部函数的变量,不管这些变量是可变还是不可变。然而,对于可变和不可变变量,内部函数的行为会有一些差异。

不可变变量

不可变变量是指其值在创建后不能被修改的变量,如整数、浮点数、字符串、元组等。在内部函数中,如果你试图修改外部函数中的不可变变量,Python 会创建一个新的局部变量,并在该作用域内使用它,而不会修改外部函数的原始变量。

def outer_function():
    x = 10  # 不可变变量
    def inner_function():
        nonlocal x  # 使用 nonlocal 声明以便修改外部函数的变量
        x = 20
    inner_function()
    print(x)  # 输出: 10

可变变量

可变变量是指其值可以在创建后修改的变量,如列表、字典等。在内部函数中,如果你修改外部函数的可变变量,实际上会修改外部函数中的原始变量,因为它们在内存中是同一个对象。

def outer_function():
    lst = [1, 2, 3]  # 可变列表
    def inner_function():
        lst.append(4)  # 修改外部函数的可变列表
    inner_function()
    print(lst) # 输出[1, 2, 3, 4]

猜你喜欢

转载自blog.csdn.net/hu_wei123/article/details/131909480