class MyClass: def __init__(self, i): self.i = i def get(self): func_name = 'function' + self.i self.func_name() # <-- this does NOT work. def function1(self): pass # do something def function2(self): pass # do something
This gives the error: TypeError: 'str' object is not callable
How would I go about doing this?
Note: self.func_name
also does not work
Using user data to call any method via send could leave room open for users to execute any method they want. send is often used to call method names dynamically—but make sure the input values are trusted and can't be manipulated by users. Golden rule is never trust any input that comes from the user.
Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function.
To do this in Python you have to access the global namespace. Python makes you do this explicitly where PHP is implicit. In this example we use the globals() function to access the global namespace. globals() returns a dictionary that includes area as a key and the value is a reference to the area() function.
def get(self): def func_not_found(): # just in case we dont have the function print 'No Function '+self.i+' Found!' func_name = 'function' + self.i func = getattr(self,func_name,func_not_found) func() # <-- this should work!
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