Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to invoke a method on an object dynamically by its name?

👍 How to invoke a method on an object dynamically by its name?

>>> # Defining class
... 
>>> class MyClass(object):
...     def __init__(self):
...         self.name = "Rishikesh Agrawani"
...         self.age = 25
...     def doStuff(self):
...         print "DETAILS:\n"
...         print "NAME: %s" % (self.name)
...         print "AGE : %d" % (self.age)
... 
>>> # Instantiation
... 
>>> obj = MyClass()
>>> func = getattr(obj, "doStuff");
>>> func()
DETAILS:

NAME: Rishikesh Agrawani
AGE : 25
>>> 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.