调用子方法时如何强制执行强制父方法调用?

时间:2021-03-11 10:58:03

标签: python inheritance methods overriding

我想要的是强制当子类从父类继承并且它覆盖父方法而不显式调用它时,会引发错误。 错误可能在错误类的初始化或调用方法时引发。

目标是确保 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

这真的可能吗? 欢迎提供任何答案或解决方法。

1 个答案:

答案 0 :(得分:2)

是的,这绝对是可能的,至少在运行时是这样。你可以创建一个 Metaclass 来修改类的创建方式,想法是通过添加一个 necessary_method 标志来更改 mother_method_called 签名,该标志仅在 {{1} } 版本被调用,否则它会引发一个 Mother。例如在 Value Error 中:

python3