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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16642145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:14:54  来源:igfitidea点击:

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

python

提问by dev-vb

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

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

How would I go about doing this?

我该怎么做呢?

Note: self.func_namealso does not work

注意:self.func_name也不起作用

采纳答案by Joran Beasley

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!

回答by sinhayash

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
    
  1. 在第 8 行使用中,

    func_name = 'function' + 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