If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it:
class CallMe: # Class def App(): # Method one ... def Foo(): # Method two ... variable = "App" # Method to call CallMe.variable() # Calling App()
But it couldn't. Any other way to do this?
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
In summary, to call a function from a string, the functions getattr() , locals() , and globals() are used. getattr() will require you to know what object or module the function is located in, while locals() and globals() will locate the function within its own scope.
You just need convert your string to a pointer by window[<method name>] . example: var function_name = "string"; function_name = window[function_name];
You can do this:
getattr(CallMe, variable)()
getattr is a builtin method, it returns the value of the named attributed of object. The value in this case is a method object that you can call with ()
You can use getattr, or you can assign bound or unbound methods to the variable. Bound methods are tied to a particular instance of the class, and unbound methods are tied to the class, so you have to pass an instance in as the first parameter.
e.g.
class CallMe: def App(self): print "this is App" def Foo(self): print "I'm Foo" obj = CallMe() # bound method: var = obj.App var() # prints "this is App" # unbound method: var = CallMe.Foo var(obj) # prints "I'm Foo"
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