通过名称动态传递参数

时间:2014-12-18 07:17:21

标签: python python-3.x dynamic parameter-passing argument-unpacking

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

像这样:

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

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

1 个答案:

答案 0 :(得分:7)

是的,keyword argument unpacking

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