I'm writing a python function that calls a function based on a parameter it takes. It looks something like this:
def match(parameter):
if parameter == 'fun1':
fun1()
elif parameter == 'fun2':
fun2()
elif parameter == 'fun3':
fun3()
All those functions being called are then defined below the match
function. Is there a more efficient way to organize the match
function? I can't find anything about pattern matching with functions, but could a data structure of some sort work?
Thanks for the help.
You can create a dictionary which stores the mapping between the function and the parameter value to call it.
For example:
def fun1():
print("I am fun1")
def fun2():
print("I am fun2")
funcs_mapping = {"fun1":fun1, "fun2":fun2}
def match(parameter):
if parameter in funcs_mapping:
funcs_mapping[parameter]()
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.