How to call multiple functions based on the input values. We can implement this with dictionary without using if-else by below:
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. The idea of this approach is to avoid conditions and directly call functions based on input values.
You can try *args method
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.