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

Question:

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

Asked By: dev-vb

||

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!
Answered By: Joran Beasley

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
    
Answered By: sinhayash
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.