Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform common post-initialization tasks in inherited classes?

The initialization process of a group of classes that share a common parent can be divided into three parts:

  • Common initialization
  • Subclass-specific initialization
  • Common post-initialization

Currently the first two parts are called from the __init__ method of each child class, but the final post-initialization part has to be called separately, for example

class BaseClass:
    def __init__(self):
        print 'base __init__'
        self.common1()

    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'


if __name__ == '__main__':
    s = Subclass1()  # Don't forget to finalize the initialization
    s.finalizeInitialization()  # now the object is fully initialized

Is there a way to not to have to call finalizeInitialization()? Or one can transfer the call to finalizeInitialization() into Subclass1's __init__ (as in S.Lott's answer). This makes the life easier, but still one has to remember to complete the initialization, this time inside the "constructor". Either way there is no way to enforce full initialization, which is what I'm looking for.

like image 284
Boris Gorelik Avatar asked Apr 27 '09 20:04

Boris Gorelik


1 Answers

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'
like image 141
Alex Martelli Avatar answered Sep 20 '22 21:09

Alex Martelli