我为继承SuperClass的子类TestClass使用了类装饰器。我在SuperClass中有一个类方法,叫做what(cls),它接受一个类。我希望能够在我的子类TestClass中装饰那个类,但它不允许我这样做。
TypeError: unbound method wrapper() must be called with TestClass instance as first argument (got nothing instead)
我尝试对TestClass对象进行实例化,然后使用该实例化来调用testclass.what(cls)
方法,这很有效,但是当我执行TestClass.what()
时,它给出了上面的错误。
def class_decorator(cls):
for attr_name in dir(cls):
attr_value = getattr(cls, attr_name)
if hasattr(attr_value, '__call__'): # check if attr is a function
# apply the function_decorator to your function
# and replace the original one with your new one
setattr(cls, attr_name, ball(attr_value))
return cls
def ball(func):
def wrapper(*args, **kwargs):
print("hello")
return func(*args, **kwargs)
return wrapper
class SuperClass:
def __init__(self):
pass
@classmethod
def what(cls):
print("testing")
@class_decorator
class TestClass(SuperClass):
def what(cls):
super().what()
TestClass.what()
期望值:
"hello"
"testing"
"hello"
"testing"
Actual: TypeError: unbound method wrapper() must be called with TestClass instance as first argument (got nothing instead)
https://stackoverflow.com/questions/56744277
复制相似问题