0
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

jonrsharpe
123k31 gold badges278 silver badges489 bronze badges
asked Sep 5, 2017 at 20:35
2
  • 3
    You explicitly call B.__init__ after C.__init__. You should be using super to manage the multiple inheritance, and read up on the MRO (method resolution order) to see the order superclasse method implementations will be called in. Commented Sep 5, 2017 at 20:36
  • You manually called the parent __init__ methods; since B.__init__() is called last, self.a = 2 is executed last (after A.__init__() was called). Commented Sep 5, 2017 at 20:38

1 Answer 1

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.

answered Sep 5, 2017 at 20:42
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.