简体   繁体   English

从 python 字典中调用函数

[英]calling functions from python dictionary

How to call multiple functions based on the input values.如何根据输入值调用多个函数。 We can implement this with dictionary without using if-else by below:我们可以在不使用 if-else 的情况下使用字典来实现这一点,如下所示:

def fun1(a, b, c) :
 ....
def fun2() :
 ....
def fun3() :
.....


dict{1 : fun1,
     2 : fun2,
     3 : fun3}

dict[1](input arguments)

But if the input parameters of different functions are different how can we pass input parameters without if-else.但是如果不同函数的输入参数不同,我们如何在没有if-else的情况下传递输入参数。 The idea of this approach is to avoid conditions and directly call functions based on input values.这种方法的思想是避免条件,直接根据输入值调用函数。

You can try *args method你可以试试 *args 方法

def fun1(a, b, c):
    print("1", a, b, c)

def fun2(a):
    print("2", a)

def fun3():
    print("3")

fun_map = {
    1 : fun1,
    2 : fun2,
    3 : fun3
}

sample calls样品调用

inputs = (1,2,3)
fun_map[1](*inputs)
# output: 1 1 2 3

inputs = (1, )
fun_map[2](*inputs)
# output: 2 1

inputs = ()
fun_map[3](*inputs)
# output: 3

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

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