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

Question:

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?
Asked By: Roy Tang

||

Answers:

Use the getattr built-in function. See the documentation

obj = MyClass()
try:
    func = getattr(obj, "dostuff")
    func()
except AttributeError:
    print("dostuff not found")
Answered By: Adam Vandenberg
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.