在 Python 的嵌套函数中使用全局变量

Using Global Variables inside a Nested Function in Python

我阅读了这段代码(在下面给出),我的理解是,如果一个变量在函数内部被声明为全局变量,并且如果它被修改,那么它的值将永久地改变。

x = 15
def change(): 
    global x 
    x = x + 5
    print("Value of x inside a function :", x) 
change() 
print("Value of x outside a function :", x)  

输出:

Value of x inside a function : 20
Value of x outside a function : 20

但是下面的代码显示了不同的输出。 x 的值在 print("After making change: ", x) 内如何不变,仍然保持 15

def add(): 
    x = 15
    
    def change(): 
        global x 
        x = 20
    print("Before making changes: ", x) 
    print("Making change") 
    change() 
    print("After making change: ", x) 

add() 
print("value of x",x) 

输出:

Before making changes:  15
Making change
After making change:  15
value of x 20

当你在 change() 函数中定义全局 x 时,嵌套在 add() 函数中;它在 add() 函数的开头定义了一个主要的全局 x 变量,该变量与局部 x = 15 不同。当你在调用 change() 之前和之后打印 x 时,你实际上在 add() 函数的开头使用了局部 x = 15,但是调用 add() 之后的最终打印将使用定义的全局 x 在 main 作用域中定义,值为 20

more explanation

add中,x不是全局变量;它在 add 本地。您也需要使其成为全局变量,以便 addchange 指的是同一个变量

def add(): 
    <b>global x</b>
    x = 15
    
    def change(): 
        global x 
        x = 20
    print("Before making changes: ", x) 
    print("Making change") 
    change() 
    print("After making change: ", x) 

add() 
print("value of x",x)

或者您需要将 change 中的 x 声明为 非本地,而不是全局的。

def add(): 
    x = 15
    
    def change(): 
        <b>nonlocal</b> x 
        x = 20
    print("Before making changes: ", x) 
    print("Making change") 
    change() 
    print("After making change: ", x) 

add() 
print("value of x",x)

在函数 add 中,变量 x 出现在封闭范围内而不是全局范围内,这就是为什么即使您使用 global关键字。
要更改此 x,您需要 nonlocal 关键字,该关键字适用于封闭范围中存在的变量。

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.


<b># global scope</b>
x = 0  


def add():
    <b># enclosing scope</b>
    x = 15

    def change():
        <b>nonlocal x</b>
        x = 20

    print("Before making changes: ", x)
    print("Making change")
    change()
    print("After making change: ", x)


add()
print("value of x", x)  # this x is global variable

</pre>

输出:

Before making changes:  15
Making change
After making change:  20
value of x 0