【发布时间】:2019-11-06 17:10:21
【问题描述】:
我正在为继承 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)
【问题讨论】:
-
听起来你的本地包装函数需要获取 self 并将其传递给 func。
标签: python python-2.7 class static python-decorators