object orientation – In what order does a class inherit from its superclasses in python?

Question:

Be the code below:

class B(A):
    def __init__(self):
        self.c  = 16
    def y(self):
        print("B.y")
    def get_c(self):
        return self.c

class C(object):
    def __init__(self):
        self.c = 5
    def y(self):
        print("C.y")
    def get_c(self):
        return self.c

class D(C, B):
    def __init__(self):
        C.__init__(self)
        B.__init__(self)

var = D()

When calling var.y() the result is Cy because D(C, B) inherits its methods from its superclasses in left-to-right order. However, when calling var.get_c() the result is 16. Why?

Answer:

According to the official documentation about classes in Python, we see in the multiple inheritance item the definition:

For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy.

That is, using your example, if a method/attribute is not found in class D , Python will look for its definition in class C , first left. If he doesn't find it, he would go deeper into the base classes of C . As it does not have it, it goes back to class B and, if not found, goes to class A , if not found, to the base classes of A . If it still doesn't find the definition, it throws the exception.

So when you run var.y() , you look for the definition of y in D, C, B, A , in that order. Finds in C , so returns Cy . When you run var.get_c() , the same thing is also found in C , returning the value of self.c , however, what happens here is that in the initializer of class D , you run the initialize of class B after the da class C and in both the self.c property is defined. That is, when executing C.__init__() , the value of self.c will be 5, but when executing B.__init__() , the value of self.c becomes 16, which explains why var.get_c() return the value 16-

Scroll to Top