Created
August 31, 2015 20:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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