【发布时间】:2021-06-09 08:45:09
【问题描述】:
我想要强制当子类从父类继承并且它覆盖父方法而不显式调用它时,会引发错误。 该错误可能在初始化错误类或调用方法时引发。
目标是确保 Mother 类的用户执行了一些体现在 Mother 方法中的操作。
例子
class Mother():
def necessary_method(self):
# do some necessary stuff
class GoodChild(Mother):
def necessary_method(self):
# necessary parent call
super().necessary_method()
class BadChild(Mother):
def necessary_method(self):
# no parent call
return
调用时:
good = GoodChild()
# works fine
bad = BadChild()
# exception could be raised here
good.necessary_method()
# works fine
bad.necessary_method()
# exception could be raised here
这真的可能吗? 欢迎任何答案或解决方法。
【问题讨论】:
标签: python inheritance methods overriding