Python supports inheritance from multiple classes. In this lesson, you’ll see:
- How multiple inheritance works
- How to use
super()to call methods inherited from multiple parents - What complexities derive from multiple inheritance
- How to write a mixin, which is a common use of multiple inheritance
A class can inherit from multiple parents. For example, you could build a class representing a 3D shape by inheriting from two 2D shapes:
class RightPyramid(Triangle, Square):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
def what_am_i(self):
return 'RightPyramid'
The Method Resolution Order (MRO) determines where Python looks for a method when there is a hierarchy of classes. Using super() accesses the next class in the MRO:
Christopher Trudeau RP Team on Feb. 8, 2021
Hi @rikhuygen,
Yep, this is one of the challenges of trying to teach mixins and object oriented lessons. The really good uses of this kind of tech tend to require more background information.
The whole “using shapes” thing to explain OO inheritance is tried and true but has its limitations. Even if I was going to write a graphic interface that used shapes, I likely wouldn’t go full OO, or if I did, the base class would be much lighter than is used in typical explanations.
The best place for things like Mixins are where you have a lot of independence and are trying to add a feature that isn’t quite specific.
For example, I recently wrote something in Django that required a special kind of identifier. The identifier was a little more complicated than just a field and needed some methods. All of this was put inside of a mixin so that any Django object that needed this kind of identifier would just mix that in. The problem with teaching with this kind of example is then you have to explain what Django is, and how it models objects and how that relates to fields and a whole bunch of other stuff.
To your specific question, the amount of code saved by using this mixin probably doesn’t warrant the hiding of the implementation that happens the way it was done. In the real world I probably wouldn’t have coded it that way, but then I wouldn’t have had a mixin example.