45
votes
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

2
Depending on your usage, you might be better off with either a list/dict of functions, or using a lambda function to pass an additional argument to the functions (the latter is mainly useful for callbacks). - sapi
This is not the code for which you got this error. when you do self.func_name you do not even access the local variable func_name. You are trying to access an instance variable named class name inside self - but such variable does not exist. - Elazar
@Elazar yes my mistake. I was translating the code and missed this one. - dev-vb
There is a subtle difference between this question and question 3061. This question focuses on calling methods within a class. 3061 focuses on regular functions. Python newbies may not be a able to apply the answers that were written there to this situation. - ChaimG
Voted to reopen. I am said newbie and it's completely non-obvious to me how this is a duplicate of the linked question. - quant

2 Answers

55
votes
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!
5
votes

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