Understanding the MRO with multiple inheritance

dieter dieter at handshake.de
Sat Mar 30 02:06:52 EDT 2019


Arup Rakshit <ar at zeit.io> writes:
> I basically had defined 4 classes. SimpleList be the base class for all the other 3 classes. SortedList and IntList both being the child of the base class SimpleList. They have a single inheritance relationship. Now I have the last class called SortedIntList which has multiple inheritance relationship with IntList and SortedList. The classes looks like:
>
> class SimpleList:
>     ...
>     def add(self, item):
>         self._items.append(item)
> ...
>
> class SortedList(SimpleList):
> ...
>     def add(self, item):
>         super().add(item)
>         self.sort()
> ...
>
> class IntList(SimpleList):
> ...
>     def add(self, item):
>         self._validate(item)
>         super().add(item)
> ...
>
> class SortedIntList(IntList, SortedList):
> ...
>
>
> Now when I call the add method on the SortedIntList class’s instance, I was expecting super.add() call inside the IntList class add method will dispatch it to the base class SimpleList.

"super" is mainly for the use case of "mixin classes".

By design, a "mixin class" must cope with an unknown inheritance structure
and it must be able to cooperate with all classes in this structure.
Especially, there must be a way to give all classes in the structure
the chance to apply a method. This way is "super".

As an example, think of "__init__". Each class in the class
structure might need to perform its own initialization.
To archieve this, "__init__" likely has the signature
"__init__(self, **kw)" and each class pickes its initialization
arguments from "kw" and then delegates to the next (in MRO) class
with "super().__init__(kw)". This class may not be a base class
of the current class.


Thus, you use "super" when you want to delegate to an unknown
class in the inheritance structure; if you want to delegate
to a specific base class, then you do not use "super"
but delegate explicitly to this class.





More information about the Python-list mailing list