2010-04-26 5 views
2

목표 : 클래스 메서드를 장식 할 수있게 만듭니다. 클래스 메쏘드가 꾸며지면 사전에 저장되어 다른 클래스 메쏘드가 문자열 메쏘드를 참조 할 수 있습니다.클래스 메서드 및 하위 클래스 메서드에 파이썬 장식 사용

동기 부여 : ASP.Net의 WebMethod와 동일한 기능을 구현하고 싶습니다. 나는 이것을 구글 앱 엔진의 최상위에 놓고있다. 그러나 그것은 내가 가지고있는 어려움의 지점에 영향을 미치지 않는다.

이 일 경우는 어떻게 보일지 :

class UsefulClass(WebmethodBaseClass): 
    def someMethod(self, blah): 
     print(blah) 

    @webmethod 
    def webby(self, blah): 
     print(blah) 

# the implementation of this class could be completely different, it does not matter 
# the only important thing is having access to the web methods defined in sub classes 
class WebmethodBaseClass(): 
    def post(self, methodName): 
     webmethods[methodName]("kapow") 

    ...  

a = UsefulClass() 
a.post("someMethod") # should error 
a.post("webby") # prints "kapow" 

이것에 대해 갈 수있는 다른 방법이있을 수 있습니다. 나는 매우 열정적이다.

답변

4

이것은 필요하지 않다. 그냥 getattr를 사용

class WebmethodBaseClass(): 
    def post(self, methodName): 
     getattr(self, methodName)("kapow") 

주의해야 할 점은 당신이 webMethods를가함으로써 사용될 수있다 유일한 방법이 사용하기위한 것 있는지 확인해야한다는 것입니다. 가장 간단한 솔루션 인 IMO는 비 웹 메소드가 밑줄로 시작하고 post 메소드가 이러한 이름을 서비스하는 것을 거부하는 규칙을 채택하는 것입니다. 당신이 정말로 장식을 사용하려면

,이 시도 :

def webmethod(f): 
    f.is_webmethod = True 
    return f 

과 메서드를 호출하기 전에 is_webmethod 속성의 존재를 확인하기 위해 post를 얻을. 언급 한 바와 같이 이것은 당신의 사양을 충족하는 가장 간단한 방법을 보일 수있을 것입니다

1

: WebmethodBaseClass에,

webmethods = {} 

def webmethod(f): 
    webmethods[f.__name__] = f 
    return f 

을하고,

def post(self, methodName): 
    webmethods[methodName](self, "kapow") 

난 당신이 다른 뭔가 (예를 들어, 별도의 네임 스페이스를 원하는 의심 서로 다른 서브 클래스 대 하나의 글로벌 webmethods 사전 ...?), 그러나 당신의 요구가 스펙과 어떻게 다른지에 대한 자세한 정보가 없으면 추측하기가 어렵습니다. 그래서이 단순한 접근 방법이 당신의 일부를 달성하지 못하는 방법을 우리에게 말해 줄 수 있습니다. 에라타, 그래서 그것은 당신이 실제로 원하는 것에 따라 풍성해질 수 있습니다.

0
class UsefulClass(WebmethodBaseClass): 

    def someMethod(self, blah): 
     print(blah) 

    @webmethod 
    def webby(self, blah): 
     print(blah) 

class WebmethodBaseClass(): 
    def post(self, methodName): 
     method = getattr(self, methodName) 
     if method.webmethod: 
      method("kapow") 

    ... 

def webmethod(f): 
    f.webmethod = True 
    return f 

a = UsefulClass() 
a.post("someMethod") # should error 
a.post("webby") # prints "kapow" 
관련 문제