In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname)
Is there something similar in python.
The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
getattr(obj, "name")(args)
hmmm... getattr(obj, funcname)(*args, **kwargs) ?
>>> s = "Abc"
>>> s.upper()
'ABC'
>>> getattr(s, "upper")()
'ABC'
>>> getattr(s, "lower")()
'abc'
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:
method_dict
using for example lambda obj: obj.method_a()
instead of function_a
etc., and then do method_dict[case](obj)
getattr()
as other answers have already mentioned, but you only need it if you really need to get the method from its name.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With