Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hygull/41f94e64b84f96fa01d04567e27eb46b to your computer and use it in GitHub Desktop.
Save hygull/41f94e64b84f96fa01d04567e27eb46b to your computer and use it in GitHub Desktop.
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