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

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!

Two things:

  1. In line 8 use,

    func_name = 'function' + str(self.i)

  2. Define a string to function mapping as,

      self.func_options = {'function1': self.function1,
                           'function2': self.function2
                           }
    
  3. So it should look as:

    class MyClass:

    def __init__(self, i):
          self.i = i
          self.func_options = {'function1': self.function1,
                               'function2': self.function2
                               }
    def get(self):
          func_name = 'function' + str(self.i)
          func = self.func_options[func_name]
          func() # <-- this does NOT work.
    
    def function1(self):
          //do something
    
    def function2(self):
          //do something
    

Tags:

Python