newb __init__ inheritance

Peter Otten __peter__ at web.de
Thu Mar 8 18:03:25 CET 2012


Maarten wrote:

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

This is WRONG:

>         super(self.__class__, self).__init__()

You have to name the current class explicitly. Consider:

>> class A(object):
...     def __init__(self):
...             print "in a"
... 
>>> class B(A):
...     def __init__(self):
...             print "in b"
...             super(self.__class__, self).__init__() # wrong
... 
>>> class C(B): pass
... 
>>> 

Can you figure out what C() will print? Try it out if you can't.
The corrected code:

>>> class B(A):
...     def __init__(self):
...             print "in b"
...             super(B, self).__init__()
... 
>>> class C(B): pass
... 
>>> C()
in b
in a
<__main__.C object at 0x7fcfafd52b10>

In Python 3 you can call super() with no args; super().__init__() do the 
right thing there.




More information about the Python-list mailing list