46
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

这给出了错误:TypeError: 'str' object is not callable

我该怎么做呢?

注意:self.func_name也不起作用

4

2 回答 2

58
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!
于 2013-05-20T03:32:32.237 回答
4

两件事情:

  1. 在第 8 行使用,

    func_name = '函数' + str(self.i)

  2. 将字符串定义为函数映射,

      self.func_options = {'function1': self.function1,
                           'function2': self.function2
                           }
    
  3. 所以它应该看起来像:

    我的班级:

    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
    
于 2013-05-20T03:51:17.767 回答