如何使用方法名赋值给变量来动态调用类中的方法


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也不工作

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!

两件事:

  1. 在第8行使用

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

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

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

    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
    

最新更新