How to perform common post-initialization tasks in inherited classes?
Version 1 - delegate everything.
class Subclass1(BaseClass):
def __init__(self):
super( Subclass1, self ).__init__()
self.specific()
super( Subclass1, self ).finalizeInitialization()
Version 2 - delegate just one step
class BaseClass:
def __init__(self):
print 'base __init__'
self.common1()
self.specific()
self.finalizeInitialization()
def common1(self):
print 'common 1'
def finalizeInitialization(self):
print 'finalizeInitialization [common2]'
def specific( self ):
# two choices:
# if this is "abstract": raise an exception
# if this is "concrete": pass
Template Method Design Pattern to the rescue:
class BaseClass:
def __init__(self, specifics=None):
print 'base __init__'
self.common1()
if specifics is not None:
specifics()
self.finalizeInitialization()
def common1(self):
print 'common 1'
def finalizeInitialization(self):
print 'finalizeInitialization [common2]'
class Subclass1(BaseClass):
def __init__(self):
BaseClass.__init__(self, self.specific)
def specific(self):
print 'specific'