Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce (with a warning) that parent functions are called by the children that override them?

I have a Parent class with many children:

class Parent(Object):
    def function(self):
        do_something()

class Child1(Parent):
    def function(self):
        super(Child1, self).function()
        do_something_else_1()

class Child2(Parent):
    def function(self):
        do_something_else_2()

and so on.

It is almost always the case that do_something() should be called by the children. I would like to throw a warning if someone writes a child class without making the super call, such as in Child2. How do I go about that?

like image 870
mdong Avatar asked Mar 14 '23 10:03

mdong


1 Answers

One way you could achieve something similar is to provide an interface for the child classes that 'forces' the writer of a subclass to get the base behaviour, without even having to call super:

class Parent(object):
    def _extra_functions(self):
        # Override me in derived classes!
        pass

    def function(self):
        # Don't override me
        do_something()
        self.extra_functions()

class Child1(Parent):
    def _extra_functions(self):
        do_something_else_1()

class Child2(Parent):
    def _extra_functions(self):
        do_something_else_2()

This is still reliant on the writer of the subclasses behaving the way you want. No matter how hard you try, any 'solution' will always be able to be worked around by a clever developer, so if you absolutely must have this then python probably isn't the right language. However, this (or other answers) make it very clear how the developers are supposed to extend this class.

like image 107
Tom Dalton Avatar answered May 02 '23 18:05

Tom Dalton