On Mon, Jun 13, 2016 at 1:13 AM, dieter <die...@handshake.de> wrote: > alanquei...@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 left-to-right. 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 Derived. 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. -- https://mail.python.org/mailman/listinfo/python-list