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
1 Answer 1
There is no search going on here. You are making explicit, direct calls to unbound methods, passing in self manually. These are simple function calls, nothing more.
So this is just a question of tracing the execution order:
D() -> D.__init__(self)
C.__init__(self)
self.a = 4
B.__init__(self)
A.__init__(self)
self.a = 1
self.a = 2
So a is assigned 4, then 1, then 2.
Comments
Explore related questions
See similar questions with these tags.
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).