Force child class to call parent method when overriding it

后端 未结 7 1932
梦谈多话
梦谈多话 2020-12-15 16:05

I am curious whether there is a way in Python to force (from the Parent class) for a parent method to be called from a child class when it is being overridden.

Examp

7条回答
  •  既然无缘
    2020-12-15 16:44

    Very little in Python is about forcing other programmers to code a certain way. Even in the standard library you will find warnings such as this:

    If the subclass overrides the constructor, it must make sure to invoke the base class constructor before doing anything else to the thread.

    While it would be possible to use a metaclass to modify subclasses' behavior, the best it could reliably do in this case would be to replace the new methods with yet another method that would take care of calling both the replaced method and the original method. However, that would have problems if the programmer then did call the parent method in the new code, plus it would lead to bad habits of not calling parent methods when one should.

    In other words, Python is not built that way.

提交回复
热议问题