动态按名称将参数传递给函数

问题描述 投票:0回答:2

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

像这样:

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

params = ("one","two","three","four",)
for var in params:
    tmp = func(var=value)
python python-3.x dynamic parameter-passing argument-unpacking
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, '!!')

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)
© www.soinside.com 2019 - 2024. All rights reserved.