Apart from the already mentioned getattr()
builtin:
As an alternative to an if-elif-else loop you can use a dictionary to map your "cases" to the desired functions/methods:
# given func_a, func_b and func_default already defined
function_dict = {
'a': func_a,
'b': func_b
}
x = 'a'
function_dict(x)() # -> func_a()
function_dict.get('xyzzy', func_default)() # fallback to -> func_c
Concerning methods instead of plain functions:
- you can just turn the above example into
method_dict
using for example lambda obj: obj.method_a()
instead of function_a
etc., and then do method_dict[case](obj)
- you can use
getattr()
as other answers have already mentioned, but you only need it if you really need to get the method from its name.
- operator.methodcaller() from the stdlib is a nice shortcut in some cases: based on a method name, and optionally some arguments, it creates a function that calls the method with that name on another object (and if you provided any extra arguments when creating the methodcaller, it will call the method with these arguments)