2016-12-02 3 views
2

내가 인자와 class을 장식하기 위해 노력하고있어하지만이 동작하지 않습니다 :파이썬 장식 클래스

이는 장식입니다 :

def message(param1, param2): 
    def get_message(func): 
     func.__init__(param1,param2) 

    return get_message 

클래스 I는 장식을 넣어 원하는

@message(param1="testing1", param2="testing2") 
class SampleClass(object): 
    def __init__(self): 
    pass 

하지만 작동하지 않습니다. 실행 중에 오류가 발생합니다. 누구든지이 문제를 알고 있습니까? 일부 값으로 클래스를 초기화하는 데코 데 이터를 만들려고합니다.

+0

데코레이터는 'SampleClass'에 바인딩 할 객체를 어디에서 반환합니까? –

+0

그래, 그게 내가 도움이 필요한거야. 나는 그 일을하는 법을 몰랐다. – IoT

+0

'get_message()'에서 무언가를 돌려 주려고 했습니까? –

답변

7

내가하려는 일을 파악하는 데 어려움이 있습니다. 인자를 취하는 데코레이터를 사용하여 클래스를 꾸미려면 한 가지 방법이 이와 같습니다.

# function returning a decorator, takes arguments 
def message(param1, param2): 
    # this does the actual heavy lifting of decorating the class 
    # this function takes a class and returns a class 
    def wrapper(wrapped): 

     # we inherit from the class we're wrapping (wrapped) 
     # so that methods defined on this class are still present 
     # in the decorated "output" class 
     class WrappedClass(wrapped): 
      def __init__(self): 
       self.param1 = param1 
       self.param2 = param2 
       # call the parent initializer last in case it does initialization work 
       super(WrappedClass, self).__init__() 

      # the method we want to define 
      def get_message(self): 
       return "message %s %s" % (self.param1, self.param2) 

     return WrappedClass 
    return wrapper 

@message("param1", "param2") 
class Pizza(object): 
    def __init__(self): 
     pass 

pizza_with_message = Pizza() 

# prints "message param1 param2" 
print pizza_with_message.get_message() 
+0

고마워요,이게 정확히 제가하고 싶었던 것입니다! – IoT