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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With