.. include:: global.rst ============================================= 13: Multiple Inheritance ============================================= Summary ============ - Single inheritance doesn't satisfy all of the requirements of domain modeling and doesn't allow for modifications to inheritance chains to introduce useful mixin - Multiple inheritance is superficially easy, but it changes the hierarchy of classes into a more general graph where each class can be inherited more than once - If you recast the idea of multiple inheritance asa way of modifying inheritance chains then the solution to the diamond problem is to linearize the inheritance graph to produce an inheritance chain in the form of the mro - The C3 algorithm can produce a linearized inheritance chain that has good properties - Not all cases of multiple inheritance can be linearized using C3 but these are problematic and best avoided - Once you understand how the mri is constructed you can start to control the way that multiple inheritance determines the mro and you can make informed choices of how to define the inheritance - The resulting mro allows each class to have a unique superclass and the super() function makes use of this to return a single superclass for any class in the mro - As the inheritance chain can vary, a given class may have a different superclass depending on which mro you are using - To make cooperative multiple inheritance work you have to make sure that each class calls the __init__ of its superclass and makes use of the dwindling parameter pattern to allow for the superclass to vary Program ============ .. literalinclude:: programs/chapterThirteen.py :language: python Program Output ================= .. code-block:: console MRO of Application: Application LoggerMixin DatabaseMixin Base object Creating Application instance: Application initialized LoggerMixin initialized DatabaseMixin initialized Base initialized