Hi @sam_the_jam,
This page has lots of documentation about Python classes: Classes
See this section: Python: Classes: Multiple Inheritance
Here’s a quote from that section:
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. Thus, if an attribute is not found in DerivedClassName
, it is searched for in Base1
, then (recursively) in the base classes of Base1
, and if it was not found there, it was searched for in Base2
, and so on.
In fact, it is slightly more complex than that; the method resolution order changes dynamically to support cooperative calls to super()
. This approach is known in some other multiple-inheritance languages as call-next-method and is more powerful than the super call found in single-inheritance languages.
A depth-first, left-to-right search for attributes consists of a search of each parent class, from the left-most to the right-most of the listings of parents in the class header, until the attribute is found. Methods are considered to be attributes. Once the attribute is found for the first time, the search ends. The search is recursive, so if any of the parent classes inherits from multiple parents, the depth-first, left-to-right search includes the parents of the parent classes.
Following is a simple example where the __init__
method is found in class A
, so that method is inherited by class C
:
class A:
def __init__(self):
self.name = "class A"
class B:
def __init__(self):
self.name = "class B"
class C(A, B):
pass
c = C()
print(c.name)
Output:
class A
EDITED on September 20, 2019 to provide the following example:
Here’s a more complex example where, due to the search order, class Z
inherits __init__
from class X
, and show_color
from class Y
:
class X:
def __init__(self, width, height, depth, color):
self.width = width
self.height = height
self.depth = depth
self.color = color
class Y:
def __init__(self, width, height, color):
self.width = width
self.height = height
self.color = color
def show_color(self):
return "I am {}.".format(self.color)
class Z(X, Y):
pass
z = Z(2, 3, 4, "green")
print(z.show_color())
Output:
I am green.
To know what arguments to pass to the __init__
method, we needed to figure out which __init__
method was inherited.
To gain more insight, you can experiment with various configurations.