Overriding methods inherited from a superclass with methods from a mixin

Ian Kelly ian.g.kelly at gmail.com
Mon Jun 13 09:17:59 EDT 2016

On Mon, Jun 13, 2016 at 1:13 AM, dieter <dieter at handshake.de> wrote:
> alanqueiros at gmail.com writes:
>> I'm trying to override methods inherited from a superclass by methods defined in a mixin class.
>> Here's an sscce:
>> https://bpaste.net/show/6c7d8d590658 (never expires)
>> I've had problems finding the proper way to do that, since at first the base class wasn't to the right and I've assumed the correct order was from left to right.
> The class' MRO ("Method Resolution Order") determines in which
> order attributes are looked up.
> Either, you must order your base classes in such a way that the MRO
> controlled lookup finds the methods you want to be used or
> you must explicitely put a definition for those methods in your
> derived class (it may have the form "overridden_method = <BaseClass>.overridden_method").
> The rules to determine the MRO are complex. The "inspect" module contains
> a function ("get_mro") to show the MRO of a given class. Use it
> to get your inheritance order right.

The details are complex, but there are two fairly simple principles
that can be relied upon:

1) Subclasses always appear before their superclasses in the MRO.
2) When a class inherits from multiple base classes, they will always
appear in the MRO in the order they appear in the class statement from

Note that neither of these rules guarantee that the classes will
appear *sequentially* in the MRO.

So in the case of mixins, listing the mixin class first is absolutely correct:

    class Derived(Mixin, Base): pass

This ensures that Mixin will always appear before Base in the MRO (and
thus override Base's methods) for Derived and for any subclass of

It is possible to concoct elaborate inheritance hierarchies in which
it is not possible to come up with an MRO that will satisfy both 1)
and 2) above. In such cases, it is also useful to know what Python
will do. Fortunately, the answer to that is also simple: the type
constructor will throw an exception. So this isn't something that
really needs to be worried about.

More information about the Python-list mailing list