class A(object):
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
A.__init__(self)
self.a = 2
self.b = 3
class C(object):
def __init__(self):
self.a = 4
self.c = 5
class D(C, B):
def __init__(self):
C.__init__(self)
B.__init__(self)
self.d = 6
obj = D()
print(obj.a)
My understanding is that python will first search class C then B then A to get a. So print(obj.a) will print out 4 when searching class C. But the answer is 2. This means that Python got self.a = 2 from class B instead of self.a = 4 from class C. Can anyone explain the reasons? Thank you
B.__init__afterC.__init__. You should be usingsuperto manage the multiple inheritance, and read up on the MRO (method resolution order) to see the order superclasse method implementations will be called in.__init__methods; sinceB.__init__()is called last,self.a = 2is executed last (afterA.__init__()was called).