Force child class to call parent method when overriding it

后端 未结 7 1950
梦谈多话
梦谈多话 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:58

    This does not relate directly to Python, it would be the case for most OO languages. You should define an abstract method in your base class, make it non-public (but available for overriding by subclasses) and also create a public template method in the parent class, that will call this abstract method (defined in your subclass). The client code will not be able to call the method in question directly, but will be able to call the template method which, in turn, will make sure that the method in question is called in the correct order/context.

    In other words, your system must not depend on the subclasses calling parent's implementation. If that is a must, then you indeed should review your implementation and decompose the method in question (eg, use the template method pattern).

    Also, some languages (like Java) implicitly call the parent's constructor, if the subclass'es constructor does not do it explicitly (does not work for plain methods though).

    In any case, please never rely on "hacks". that is not the right way to solve problems.

提交回复
热议问题