简体   繁体   English

具有可变数量参数的python函数字典

[英]python function dictionary with variable number of parameters

I am trying to create a dictionary which maps strings to functions. 我正在尝试创建一个将字符串映射到函数的字典。 The problem is, the functions can have different parameter lengths. 问题是,函数可以有不同的参数长度。 Is there a way to handle this. 有没有办法解决这个问题。

For ex: 例如:

myFuncDict
{
'A' : a    ----> def a(param1, param2)
'B  : b    ----> def b(param1)
'C' : c    ----> def c(param1, param2, param3)
}

I want to call functions like:
def test(k):
 myFuncDict[k](params)

How can i achieve this? 我怎样才能实现这一目标? kwargs or args is one way to go, but not sure how to handle the above using those without sending extra parameters. kwargs或args是一种可行的方法,但不知道如何使用那些没有发送额外参数的方法来处理上述问题。

Python actually makes this quite simple. Python实际上使这很简单。 You can simply unpack your container of arguments into the function call using the unpacking operator * . 您可以使用解包运算符*将参数容器解压缩到函数调用中。 Here is an example: 这是一个例子:

def a(x):
    print(x)

def b(x, y):
    print x, y

dic = {'a': a, 'b': b}


def call_func(func, params):
    dic[func](*params) # *params is the magic.

call_func('a', (1))
call_func('b', (1, 2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM