如何解决如何解决由于使用装饰器添加方法类而导致的错误?
我正在尝试使用装饰器添加方法类,但测试后出现错误
第一种方式:
from functools import wraps
def add_class_method(name_class):
def real_decorator(items):
@wraps(items)
def class_method(self,*args,**kwargs):
return items(*args,**kwargs)
setattr(name_class,items.__name__,classmethod(class_method))
return class_method
return real_decorator
错误:
class_method() 缺少 1 个必需的位置参数:'self'
第二种方式:
def add_class_method(name_class):
def real_decorator(items):
@classmethod
@wraps(items)
def class_method(self,**kwargs):
return items(*args,**kwargs)
setattr(name_class,class_method)
return class_method
return real_decorator
错误:
'classmethod' 对象不可调用
class A:
pass
@add_class_method(A)
def foo():
return "Hello!"
assert A.foo() == "Hello!"
哪种方式更好,我应该更改/添加什么?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。