Python 3.x 如何构建这个“类装饰器”?
我正在制作一个简单的装饰器,以大写形式输出返回值。这是我尝试的代码:Python 3.x 如何构建这个“类装饰器”?,python-3.x,decorator,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 m
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'
TypeError: __call__() takes 1 positional argument but 2 were given
然后我稍微修改了构造函数(def\uuuu init\uuu(self,func,msg=None):
)并得到以下错误:
TypeError: __init__() missing 1 required positional argument: 'msg'
TypeError: __call__() takes 1 positional argument but 2 were given
请帮我解决它。谢谢修饰函数的参数被传递到
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法,而不是构造函数\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
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
修饰函数的参数被传递给\uuuuu call\uuuuu
方法,而不是构造函数\uuuuuu init\uuuuu
:
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