2012-12-13 72 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()