For example, I have a
class BaseHandler(object):
def prepare(self):
self.prepped = 1
I do not want everyone that subclasses BaseHandler and also wants to implement prepare to have to remember to call
super(SubBaseHandler, self).prepare()
Is there a way to ensure the superclass method is run even if the subclass also implements prepare?
I have solved this problem using a metaclass.
Using a metaclass allows the implementer of the
BaseHandlerto be sure that all subclasses will call the superclassesprepare()with no adjustment to any existing code.The metaclass looks for an implementation of
prepareon both classes and then overwrites the subclass prepare with one that callssuperclass.preparefollowed bysubclass.prepare.Using it looks like this: