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?
To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.
Use getattr() to call a class method by its name as a string Call getattr(object, name) using a method name in string form as name and its class as object . Assign the result to a variable, and use it to call the method with an instance of the class as an argument.
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method.
Use the getattr
built-in function. See the documentation
obj = MyClass() try: func = getattr(obj, "dostuff") func() except AttributeError: print("dostuff not found")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With