Implicitly invoking parent class initializer

Posted by Matt Joiner on Stack Overflow See other posts from Stack Overflow or by Matt Joiner
Published on 2010-03-01T09:17:57Z Indexed on 2010/04/30 8:27 UTC
Read the original article Hit count: 435

class A(object):
    def __init__(self, a, b, c):
        #super(A, self).__init__()
        super(self.__class__, self).__init__()


class B(A):
    def __init__(self, b, c):
        print super(B, self)
        print super(self.__class__, self)
        #super(B, self).__init__(1, b, c)
        super(self.__class__, self).__init__(1, b, c)

class C(B):
    def __init__(self, c):
        #super(C, self).__init__(2, c)
        super(self.__class__, self).__init__(2, c)
C(3)

In the above code, the commented out __init__ calls appear to the be the commonly accepted "smart" way to do super class initialization. However in the event that the class hierarchy is likely to change, I have been using the uncommented form, until recently.

It appears that in the call to the super constructor for B in the above hierarchy, that B.__init__ is called again, self.__class__ is actually C, not B as I had always assumed.

Is there some way in Python-2.x that I can overcome this, and maintain proper MRO when calling super constructors without actually naming the current class?

© Stack Overflow or respective owner

Related posts about python

Related posts about python-2.x