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

Mih*_*hir 4 python nested global function

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

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)  
Run Code Online (Sandbox Code Playgroud)

输出:

Value of x inside a function : 20
Value of x outside a function : 20
Run Code Online (Sandbox Code Playgroud)

但下面的代码显示了不同的输出。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) 

Run Code Online (Sandbox Code Playgroud)

输出:

Before making changes:  15
Making change
After making change:  15
value of x 20
Run Code Online (Sandbox Code Playgroud)

che*_*ner 5

add,x不是全局变量;它是本地的add。您也需要使其成为全局变量,以便addchange引用相同的变量

def add(): 
    global x
    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)
Run Code Online (Sandbox Code Playgroud)

或者您需要将xin声明changenonlocal,而不是 global 。

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

add() 
print("value of x",x)
Run Code Online (Sandbox Code Playgroud)