我有一个继承自另一个
base
类的类,并且想使用装饰器
class Base:
def Checkpoint(func: Any) -> Any:
def inner(self, *args, **kwargs):
return f"calling {func} from a decorator"
return inner
class RegularClass(Base):
@Checkpoint
def DoSomething1(self):
print("Doing something 1")
@Checkpoint
def DoSomething2(self):
print("Doing something 1")
如果我将
Checkpoint
移动到 RegularClass
内,它就会起作用;但我希望我能将 Checkpoint
保留在 Base
类中,这样我就可以在多个类中重用它
当我尝试实例化
Undefined name 'Checkpoint'
并使用它时,出现 RegularClass
错误。正在关注这篇文章,不确定我错过了什么。
我也尝试过
@Base.Checkpoint
,但这似乎也不起作用。这是我遇到的错误
Base.Checkpoint() missing 1 required positional argument: 'func'
不确定为什么要在
()
之后添加 Base.Checkpoint
?我不需要 ()
装饰器,对吗?
有人有什么想法吗? Python版本:3.11.4.
您是否尝试过在
Checkpoint
课程之外定义您的 Base
?即使你的 RegularClass
是 Base
的子类,它也无法访问装饰器函数。如果你这样做:
def Checkpoint(func):
def inner(self, *args, **kwargs):
return f"calling {func} from a decorator"
return inner
class RegularClass:
@Checkpoint
def DoSomething1(self):
print("Doing something 1")
@Checkpoint
def DoSomething2(self):
print("Doing something 1")
那么你就不会得到任何错误。我还删除了类型提示,因为它们也在我的 IDE 中生成错误 (
"Any" is not defined.
)。