首页 > 解决方案 > 如何在python中将函数的位置参数声明为全局变量?

问题描述

如何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

标签: python

解决方案


您不需要使用全局变量,但如果这样做,请执行如下 for 循环:

var_names = ["v1", "v2"]
for i in var_names:
    globals()[i] = f"{i}-new"

要访问新的全局变量,只需键入:globals()["var_name"]


推荐阅读