Multiple Inheritance#
Classes can inherit from more than one class at the same time, which we called multiple inheritance.
Syntax
To inherit from multiple classes, reference them in a comma separated list in the class definition
class ParentClassName(ParentClass1Name, ParentClass2Name, ..., ParentClassNName):
Note
Check the next page for an example!
Method Resolution Order#
With multiple inheritance, parent classes may or may not implement any given method. Therefore the Python interpreter needs to follow a principled procedure to select which method from any number of parent classes to use.
This is defined by the Method Resolution Order (MRO), which to summarise works as follows:
The parent classes are searched from left to right as defined and followed up the chain.
However if two inherited classes are on the same “level” in an inheritance chain they are searched in the left to right order as defined.
If you’re interested in learning more, follow this link https://docs.python.org/3/howto/mro.html#examples
super()#
Due to the MRO, super() will refer to the leftmost parent class. However in
many cases you would need to also properly initialise attributes from more than
one parent class.
To achieve this you will need to manually call __init__ on each parent
class.
Example
class A:
def __init__(self):
print("A")
class B:
def __init__(self):
print("B")
class C(A, B):
def __init__(self):
A.__init__(self)
B.__init__(self)
print("C")
instance = C()
Mixins#
A mixin class is a way of adding functionality through multiple inheritance. Mixin classes are typically independent from other classes.
Mixins can be used to simplify your code as terminating child classes can combine multiple mixins to achieve their desired functionality. This also increases code resuse - functionality only needs to be written in a single mixin and can be reused by many classes.
Example
Note
The next page includes a complete working example of a mixin.
In the example below classes A and B are mixins that add methods
cool_method and awesome_method respectively.
We can then pick and choose from A and B to add functionality from
classes e.g.
class
Cuses bothAandBclass
Duses onlyB
class A:
def cool_method(self):
print("Cool method")
class B:
def aweseome_method(self, x):
print(x * 10)
class C(A, B):
def __init__(self):
print("C")
class D(B):
def __init__(self):
print("D")
c = C()
c.cool_method()
c.aweseome_method(3)
d = D()
d.awesome_method(10)