Skip to content

Instantly share code, notes, and snippets.

@indraniel
Created August 31, 2015 20:31
Show Gist options
  • Save indraniel/da11c4f79c79b5e6bfb8 to your computer and use it in GitHub Desktop.
Save indraniel/da11c4f79c79b5e6bfb8 to your computer and use it in GitHub Desktop.
Python: How to dynamically call a method/function given a string of its name
# Based on reading : http://stackoverflow.com/questions/7936572/python-call-a-function-from-string-name
# http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python
class Foo(object):
def dynamic_call(self, attribute_name):
method_name = 'calculate_' + attribute_name # e.g. given attribute name "baz" call method "calculate_baz"
func = getattr(self, method_name) # find method that located within the class
func() # execute the method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment