2012-12-13 57 views
1
class Test: 
@staticmethod 
    def call(): 
    return 
def callMethod1(): 
    return 
def callMethod2(): 
    return 
var methodName='Method1' 

我想用"call"+methodName()调用呼叫callMethod1callMethod2()。即在php中,我们打电话给任何成员使用T est->{"call".methodName}()如何在没有eval()方法的python中实现这一点。的Python:按名称调用类及类方法使用eval

回答

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

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

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

Test.call("method1") 
2

您可以使用该类上的getattr来获取该方法。我不知道究竟是如何将它集成到你的代码,但也许这个例子可以帮助:

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

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

但是,你将不得不作为第一个参数添加到self你的方法第一。

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()