[英]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
的。 您要么也需要使其成為全局變量,以便add
和change
引用同一個變量
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.