Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically call methods within a class using method-name assignment to a variable [duplicate]

Tags:

python

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

like image 417
dev-vb Avatar asked May 20 '13 03:05

dev-vb


People also ask

How do you call a method dynamically?

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.

What is the __ call __ method?

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.

How do you call a function dynamically in Python?

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.


1 Answers

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! 
like image 121
Joran Beasley Avatar answered Sep 22 '22 09:09

Joran Beasley