按名称动态传递参数到函数

4

是否可以动态设置传递给函数的参数名称?

像这样:

def func(one=None, two=None, three=None, four=None):
    ...

params = ("one","two","three","four",)
for var in params:
    tmp = func(var=value)
2个回答

12

是的,使用关键字参数拆包可以实现:

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, '!!')

这太聪明了!谢谢。 - Jeremy

0
如果有人想要传递动态参数,但这些参数不是键值对参数,你可以创建一个动态的列表,并在函数调用中传递它。
*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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接