Python decorating class

2020-07-18 07:45发布

问题:

I'm trying to decorate a class with arguments but cannot get it to work:

This is the decorator:

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

   return get_message

class where I want to put the decorator

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

But this is not working , I am getting an error when running this. Does anyone know what the problem ?, I am trying to create a decorator to initialise classes with some values.

回答1:

I'm having trouble figuring out what you're trying to do. If you want to decorate a class with a decorator that takes arguments, one way to do it is like this.

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