newb __init__ inheritance

Maarten maarten.sneep at knmi.nl
Thu Mar 8 11:30:17 EST 2012


On Thursday, March 8, 2012 4:25:06 PM UTC+1, hyperboogie wrote:

> My question is if __init__ in the descendant class overrides __init__
> in the parent class how can I call the parent's __init__ from the
> descendant class - I just overrode it didn't I?
> 
> Am I missing something more fundamental here?

No, you're not. 

However, you can explicitly call the __init__() method of a particular class. Hard-coding the class gives you:

class A(object):
    def __init__(self):
        print("In A")

class B(A):
    def __init__(self):
        A.__init__(self)
        print("In B")

Alternatively you can figure out the parent class with a call to super:

class C(A):
    def __init__(self):
        super(self.__class__, self).__init__()
        print("In C")

a = A() (prints "In A")
b = B() (prints "In A", "In B" on two lines)
c = C() (prints "In A", "In C" on two lines)

Hope this helps.

Maarten



More information about the Python-list mailing list