In what order does a class inherit from its python superclasses?

Asked

Viewed 149 times

3

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()

By calling var.y() the result is C.y for D(C, B) inherits your methods from your superclasses by following an order from left to right. However, when calling var.get_c() the result is 16. Why?

1 answer

2


In accordance with the official documentation about classes in Python, we see in the item of multiple inheritance 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 is an overlap in the Hierarchy.

That is, using your example, if a method/attribute is not found in the class D, Python will search by its definition in the class C, first on the left. If not found, would go deeper, for the basic classes of C. Since he doesn’t own it, he goes back to class B and if you don’t, go to class A, if not, for the basic classes of A. If you still can’t find the definition, fire the exception.

Therefore, when executed var.y(), the definition of y in D, C, B, A, in this order. You find in C, therefore returns C.y. When executed 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 class initializer D, you run the class initialize B after the class C and in both the property self.c is defined. That is, when executed C.__init__(), the value of self.c will be 5, but when executed B.__init__(), the value of self.c becomes 16, which explains why var.get_c() return the value 16-

Browser other questions tagged

You are not signed in. Login or sign up in order to post.