Derek Gu
Derek Gu

Reputation: 21

python 3 class inheritance issue

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

Upvotes: 0

Views: 45

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121914

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.

Upvotes: 1

Related Questions