1
class A(object):
    def __init__(self):
        print('A.__init__()')

class D(A):
    def __init__(self):
        super(A, self).__init__()
        print('D.__init__()')

D()

The output is:

D.__init__()

This is unexpected to me. According to my understanding, super(A, self).__init__() should have called A's ctor, thus should have printed "A.init()".

I have read a few other questions about super() but I don't think they answer my question exactly.

My python is 3.5.3.

vaultah
  • 44,105
  • 12
  • 114
  • 143
Roy
  • 880
  • 1
  • 12
  • 27

1 Answers1

2

The reason your not getting what you expect is because you are calling the __init__() function of A's parent class - which is object - so A's __init__() is never called. You need to do super(D, self).__init__() instead to call the constructor of D's parent class, A:

>>> class A(object):
    def __init__(self):
        print('A.__init__()')


>>> class D(A):
    def __init__(self):
        super(D, self).__init__() # Change A to D
        print('D.__init__()')


>>> D()
A.__init__()
D.__init__()
<__main__.D object at 0x7fecc5bbcf60>
>>> 

Also, note that in Python 3 you no longer have to explicitly inherit from object. All classes inherit from object by default. See Section 3.3 New-style and old-style classes in Python 2's docs for a more detailed overview.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
  • Thank you for the detailed answer. And for the extra tip on `object`. – Roy Jun 28 '17 at 19:56
  • And for the benefit of other readers. I also found Jean-F. F.'s comment to the OP useful, i.e. check out https://stackoverflow.com/questions/9575409/calling-parent-class-init-with-multiple-inheritance-whats-the-right-way, which in term refer to https://rhettinger.wordpress.com/2011/05/26/super-considered-super/. – Roy Jun 28 '17 at 19:57