Internal functions access (variable, immutable) variables of external functions

In Python, inner functions can access the variables of outer functions, regardless of whether those variables are mutable or immutable. However, there are some differences in the behavior of inner functions for mutable and immutable variables.

immutable variables

Immutable variables refer to variables whose values ​​cannot be modified after creation, such as integers, floating point numbers, strings, tuples, etc. In an inner function, if you try to modify an immutable variable in the outer function, Python will create a new local variable and use it within that scope without modifying the outer function's original variable.

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

mutable variable

Mutable variables are variables whose values ​​can be modified after creation, such as lists, dictionaries, etc. In the inner function, if you modify the mutable variable of the outer function, you will actually modify the original variable in the outer function, because they are the same object in memory.

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

Guess you like

Origin blog.csdn.net/hu_wei123/article/details/131909480