Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method from string

Tags:

python

oop

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?

like image 766
Sirupsen Avatar asked Dec 06 '09 14:12

Sirupsen


People also ask

How do you call a method in a string?

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.

Can you use a string to call a function?

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.

How do you call a function inside a string in JavaScript?

You just need convert your string to a pointer by window[<method name>] . example: var function_name = "string"; function_name = window[function_name];


2 Answers

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 ()

like image 114
Nadia Alramli Avatar answered Sep 17 '22 20:09

Nadia Alramli


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" 
like image 37
Dave Kirby Avatar answered Sep 21 '22 20:09

Dave Kirby