2016-12-02 91 views
2

我想装饰带有参数的class,但不能得到它的工作:Python的装饰类

这是装饰:

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

    return get_message 

类,我希望把装饰

@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