是否可以动态设置传递给函数的参数名称?
像这样:
def func(one=None, two=None, three=None, four=None):
...
params = ("one","two","three","four",)
for var in params:
tmp = func(var=value)
是的,使用 关键字参数解包:
def func(one=None, two=None, three=None, four=None):
return (one, two, three, four)
params = ("one", "two", "three", "four")
for var in params:
tmp = func(**{var: "!!"})
print(tmp)
输出:
('!!', None, None, None)
(None, '!!', None, None)
(None, None, '!!', None)
(None, None, None, '!!')
如果有人正在寻找传递动态参数,但这些参数不是键值对参数。您可以创建动态
列表
并在函数调用中像这样传递它
*list
例如
def fun(a,b,c,d):
pass
dynamic_list = []
if True:
dynamic_list.append(2)
if True:
dynamic_list.append(2)
if True:
dynamic_list.append(2)
if True:
dynamic_list.append(2)
fun(*dynamic_list)