我该如何构建这个“类装饰器”?

时间:2019-07-31 12:17:41

标签: python-3.x decorator

我正在制作一个简单的装饰器,该装饰器以大写形式输出返回的值。这是我尝试的代码:

class UpperDecorator:
    def __init__(self, func, msg):
        self.func = func 
        self.msg = msg

    def __call__(self):
        res = self.func(self.msg)
        return res.upper()


@UpperDecorator
def message_app(msg):
    return msg

res = message_app('Hi')
print(res)

运行代码时出现此错误:

TypeError: __init__() missing 1 required positional argument: 'msg'

然后我稍微修改了构造函数(def __init__(self, func, msg=None):)并得到此错误:

TypeError: __call__() takes 1 positional argument but 2 were given

请帮我解决。谢谢

1 个答案:

答案 0 :(得分:4)

装饰函数的参数传递给__call__方法,而不传递给构造函数__init__

class UpperDecorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        res = self.func(*args, **kwargs)
        return res.upper()

@UpperDecorator
def message_app(msg):
    return msg

res = message_app('Hi')
print(res)

打印:

HI