Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a function on an object dynamically by name? [duplicate]

Tags:

python

In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?

That is:

obj = MyClass() # this class has a method doStuff() func = "doStuff" # how to call obj.doStuff() using the func variable? 
like image 383
Roy Tang Avatar asked Oct 17 '10 03:10

Roy Tang


People also ask

How do you call a function from an object in Python?

To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.

How do you call a function from a name stored in a string Python?

Use getattr() to call a class method by its name as a string Call getattr(object, name) using a method name in string form as name and its class as object . Assign the result to a variable, and use it to call the method with an instance of the class as an argument.

Can you use a string to call a function?

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.


1 Answers

Use the getattr built-in function. See the documentation

obj = MyClass() try:     func = getattr(obj, "dostuff")     func() except AttributeError:     print("dostuff not found") 
like image 100
Adam Vandenberg Avatar answered Sep 29 '22 04:09

Adam Vandenberg