我正在制作一个简单的装饰器,该装饰器以大写形式输出返回的值。这是我尝试的代码:
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
请帮我解决。谢谢
答案 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