Python decorating class

断了今生、忘了曾经 提交于 2019-12-04 10:25:24

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!