Python:调用类&使用eval按名称类方法

时间:2012-12-13 09:20:59

标签: python dynamic reflection python-2.6

class Test:
 @staticmethod
   def call():
     return
 def callMethod1():
    return
 def callMethod2():
    return
var methodName='Method1'

我想使用callMethod1在call()中调用callMethod2"call"+methodName()。即,在php中我们使用T est->{"call".methodName}()调用任何成员如何在没有eval()方法的python中实现这一点。

3 个答案:

答案 0 :(得分:3)

class Test:
   @staticmethod
   def call(method):
      getattr(Test, method)()

   @staticmethod
   def method1():
      print('method1')

   @staticmethod
   def method2():
      print('method2')

Test.call("method1")

答案 1 :(得分:2)

您可以在课程上使用getattr来获取该方法。我不确定如何将它集成到您​​的代码中,但也许这个例子会有所帮助:

def invoke(obj, methodSuffix):
    getattr(obj, 'call' + methodSuffix)()

x = Test()
invoke(x, 'Method1')

但是你必须首先添加self作为方法的第一个参数。

答案 2 :(得分:0)

你应该清理你的示例代码,缩进被破坏,你没有self方法。

使用getattr(self, "call"+methodName)()。此外,call方法不应该是静态方法,因为它需要访问类来调用其他方法。

class Test:
    def __init__(self, methodName):
        self.methodName = methodName

    def call(self):
        return getattr(self, "call" + self.methodName, "defaultMethod")()

    def callMethod1(self): pass
    def callMethod2(self): pass
    def defaultMethod(self): pass

t = Test("Method1")
t.call()
相关问题