【问题标题】:How do I build this `class decorator`?如何构建这个“类装饰器”?
【发布时间】:2019-07-31 12:17:41
【问题描述】:

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

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

请帮我解决。谢谢

【问题讨论】:

    标签: python-3.x decorator


    【解决方案1】:

    装饰函数的参数传递给__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
    

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 2015-03-28
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 2018-01-22
      • 2015-05-14
      相关资源
      最近更新 更多