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

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

Use the getattr built-in function. See the documentation

obj = MyClass()
try:
    func = getattr(obj, "dostuff")
    func()
except AttributeError:
    print("dostuff not found")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoy TangView Question on Stackoverflow
Solution 1 - PythonAdam VandenbergView Answer on Stackoverflow