簡體   English   中英

在 Python 中的嵌套 Function 中使用全局變量

[英]Using Global Variables inside a Nested Function in Python

我閱讀了這段代碼(如下所示),我的理解是,如果一個變量在 function 中聲明為全局變量,並且如果它被修改,那么它的值將永久更改。

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)  

Output:

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

但是下面的代碼顯示了不同的 output。 為什么 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) 

Output:

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

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)

或者您需要將x in change聲明為nonlocal ,而不是 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)

當您在 change() function 中定義全局x時,嵌套在 add() function 中; 它定義了一個主全局x變量,該變量不同於 add() function 開頭的局部x = 15 當你在調用 change() 之前和之后打印x時,實際上在 add() function 的開頭使用本地x = 15 ,但調用 add() 之后的最終打印將使用在 main scope 中定義的已定義全局x並具有值20

更多解釋

在 function 中add變量x存在於封閉的 scope 而不是全局 scope 中,這就是為什么即使您使用global關鍵字x也不會改變。
要更改此x ,您需要適用於封閉 scope 中存在的變量的nonlocal關鍵字。

nonlocal語句導致列出的標識符引用最近的封閉 scope 中先前綁定的變量,不包括全局變量。


# global scope
x = 0  


def add():
    # enclosing scope
    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)  # this x is global variable

Output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM