[英]How to declare a positional parameter of a function as a global variable in python?
如何將下面function中的位置參數var
聲明為全局變量?
v1 = 'a1'
v2 = 'a2'
# and there may be other variables like v3, v4
def test(var):
global var
var += '-new'
test(v1)
print(v1) # I hope this can be a1-new
test(v2)
print(v2) # I hope this can be a2-new
您不需要使用全局變量,但如果這樣做,請執行如下 for 循環:
var_names = ["v1", "v2"]
for i in var_names:
globals()[i] = f"{i}-new"
要訪問新的全局變量,只需鍵入: globals()["var_name"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.