Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Python method by name

Tags:

python

If I have an object and a method name in a string, how can I call the method?

class Foo:     def bar1(self):         print 1     def bar2(self):         print 2  def callMethod(o, name):     ???  f = Foo() callMethod(f, "bar1") 
like image 324
Jazz Avatar asked Aug 19 '10 12:08

Jazz


People also ask

How can I call a function given its name as 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.

How do you call a function name?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.

How do you call a function dynamically in Python?

To do this in Python you have to access the global namespace. Python makes you do this explicitly where PHP is implicit. In this example we use the globals() function to access the global namespace. globals() returns a dictionary that includes area as a key and the value is a reference to the area() function.


2 Answers

Use the built-in getattr() function:

class Foo:     def bar1(self):         print(1)     def bar2(self):         print(2)  def call_method(o, name):     return getattr(o, name)()   f = Foo() call_method(f, "bar1")  # prints 1 

You can also use setattr() for setting class attributes by names.

like image 109
Enrico Carlesso Avatar answered Sep 18 '22 20:09

Enrico Carlesso


I had similar question, wanted to call instance method by reference. Here are funny things I found:

instance_of_foo=Foo()  method_ref=getattr(Foo, 'bar') method_ref(instance_of_foo) # instance_of_foo becomes self  instance_method_ref=getattr(instance_of_foo, 'bar') instance_method_ref() # instance_of_foo already bound into reference 

Python is amazing!

like image 40
Yaroslav Stavnichiy Avatar answered Sep 19 '22 20:09

Yaroslav Stavnichiy