4 回答

TA貢獻1859條經驗 獲得超6個贊
如果在全局范圍內定義的變量名稱也在函數的局部范圍內使用,則會發生兩件事:
您正在進行讀取操作(例如:簡單地打印它),那么變量引用的值與全局對象相同
x = 3
def foo():
print(x)
foo()
# Here the x in the global scope and foo's scope both point to the same int object
您正在進行寫操作(示例:為變量賦值),然后在函數的局部范圍內創建一個新對象并引用它。這不再指向全局對象
x = 3
def bar():
x = 4
bar()
# Here the x in the global scope and bar's scope points to two different int objects
但是,如果你想在全局范圍內使用一個變量并想在局部范圍內對其進行寫操作,你需要將它聲明為global
x = 3
def bar():
global x
x = 4
bar()
# Both x points to the same int object

TA貢獻1835條經驗 獲得超7個贊
很明顯,程序,機器在映射中工作
bar()
# in bar function you have x, but python takes it as a private x, not the global one
def bar():
x = 4
foo()
# Now when you call foo(), it will take the global x = 3
# into consideration, and not the private variable [Basic Access Modal]
def foo():
print(x)
# Hence OUTPUT
# >>> 3
現在,如果你想打印4, not 3,這是全局的,你需要在 foo() 中傳遞私有值,并使 foo() 接受一個參數
def bar():
x = 4
foo(x)
def foo(args):
print(args)
# OUTPUT
# >>> 4
或者
global在你的內部使用bar(),這樣機器就會明白xbar 的內部是全局 x,而不是私有的
def bar():
# here machine understands that this is global variabl
# not the private one
global x = 4
foo()
添加回答
舉報