2012-03-28 3 views
14

누군가 간단한 예제를 보여 주시겠습니까? 나는 브루스 에켈 (Bruce Eckel)가 herepython : 데코레이터를 클래스로 정의하여 클래스 장식하기

다음 작품 설명으로 수업을하지 함수를 사용하여 제외 PEP 3129 사용하여 파이썬 2.6에 구현 된 내용을 달성하기 위해 노력하고있어 제외

class Decorator(object): 
    def __init__(self, arg): 
     self.arg = arg 

    def __call__(self, cls): 
     def wrappedClass(*args): 
      return cls(*args) 
     return type("TestClass", (cls,), dict(newMethod=self.newMethod, classattr=self.arg)) 

    def newMethod(self, value): 
     return value * 2 

@Decorator("decorated class") 
class TestClass(object): 
    def __init__(self): 
     self.name = "TestClass" 
     print "init %s"%self.name 

    def TestMethodInTestClass(self): 
     print "test method in test class" 

    def newMethod(self, value): 
     return value * 3 

을 위에서, wrappedClass는 아니다 클래스 유형을 리턴하도록 조작 된 함수. 다음과 같이 동일한 호출 가능 코드를 작성하려고합니다.

def __call__(self, cls): 
     class wrappedClass(cls): 
      def __init__(self): 
       ... some code here ... 
     return wrappedClass 

어떻게 수행됩니까? 편집 : 나는

+0

게시 한 코드를 사용해 보았습니까? 그것은 작동해야합니다. –

+0

함수를 사용하는 첫 번째 부분이 작동하지 않습니다. 그래도 wrappedClass를 진정한 클래스로 작성하겠습니까? – tsps

+1

데코레이터는 어떻게해야하나요? 나는이 코드가 무엇을해야할지 모른 채 "어떤 코드"에 들어가야하는 코드를 말할 수 없다. –

답변

13

당신이 new_method()을 덮어 쓰려면이 그냥 해 "... 여기 몇 가지 코드 ..." "" ""에 들어가는 것을 완전히 확실하지 않다 :

class Decorator(object): 
    def __init__(self, arg): 
     self.arg = arg 
    def __call__(self, cls): 
     class Wrapped(cls): 
      classattr = self.arg 
      def new_method(self, value): 
       return value * 2 
     return Wrapped 

@Decorator("decorated class") 
class TestClass(object): 
    def new_method(self, value): 
     return value * 3 

__init__()을 변경하지 않으려는 경우이를 덮어 쓸 필요가 없습니다.

2

이 후, 클래스 NormalClass는 ClassWrapper 예를된다 :

def decorator(decor_arg): 

    class ClassWrapper: 
     def __init__(self, cls): 
      self.other_class = cls 

     def __call__(self,*cls_ars): 
      other = self.other_class(*cls_ars) 
      other.field += decor_arg 

    return ClassWrapper 

@decorator(" is now decorated.") 
class NormalClass: 
    def __init__(self, name): 
     self.field = name 

    def __repr__(self): 
     return str(self.field) 

테스트 :

if __name__ == "__main__": 

    A = NormalClass('A'); 
    B = NormalClass('B'); 

    print A 
    print B 
    print NormalClass.__class__ 

출력 :

A는 이제 장식되어 있습니다.
B가 장식되었습니다.
__main __. classWrapper

+2

__call__ 메소드에서 'other'변수를 반환하는 것을 잊었습니다. –

관련 문제