2012-12-13 2 views
1
내가 "call"+methodName() 사용) (통화 callMethod1 또는 callMethod2를 호출 할
class Test: 
@staticmethod 
    def call(): 
    return 
def callMethod1(): 
    return 
def callMethod2(): 
    return 
var methodName='Method1' 

를 사용하여 이름으로 클래스 및 클래스 메소드를 호출합니다. 즉 PHP에서 우리는 T est->{"call".methodName}()을 사용하여 어떤 멤버라도 호출 할 수 있습니다. 어떻게 이것을 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 메소드는 다른 메소드를 호출하기 위해 클래스에 액세스해야하기 때문에 static 메소드가 아니어야합니다.

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