Reputation: 945
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.
Upvotes: 1
Views: 629
Reputation: 22953
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.
Upvotes: 2