[英]Python: Change a global variable, which comes from a function parameter
有沒有辦法讓函數的參數,它是一個全局變量,在函數本身中你可以改變這個變量的值。 這樣你就有一個全局變量作為函數的參數。 在函數本身中,您可以更改此全局變量的值。 例如:
x = 2
a = 5
def minus_one(x):
x -= 1 #take the global x
minus_one(x)
print(x) #Should print 1
minus_one(a)
print(a) #Should print 4
是的,你可以做類似的事情。
x = 2
def minus_one(var_name):
globals()[var_name] -= 1 # This accesses the global dict
minus_one('x') # Note that you must pass the variable name as string here
print(x) # Prints 1
雖然,這根本不推薦。
這可能會導致極難發現的錯誤。
幾乎總是有更好的方法來做到這一點
有點丑
一般來說,知道全局字典存在是好的。 知道你不應該使用它更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.