Skip to content

Python Inheritance, Polymorphism, and MRO

Step 28 of 41

Python Multiple Inheritance: C3 MRO, Diamonds, and super

Introduction

Python multiple inheritance resolves attributes through a class’s method resolution order, or MRO. In a diamond, the second branch can provide a method before the shared ancestor is considered. A cooperative super() call follows that same order rather than jumping directly to one written parent.

This lesson continues PCAP-31-03 objective 4.5 in Object-Oriented Programming (34% of the score, 12 of 40 items), using class metadata from 4.4 and initialization from 4.6. You will trace diamonds, diagnose inconsistent hierarchies, and follow cooperative calls.

Learning objectives

After this lesson you can:

  1. Write a class with several parents and list its direct parents with __bases__.
  2. Predict which parent's method or class variable is used, from the order of the base classes.
  3. Display the full search order with __mro__ and explain what it contains.
  4. Resolve a diamond and explain why its shared ancestor follows the classes derived from it.
  5. Trace constructor chains with explicit parent calls and with super().
  6. Recognise an inconsistent order of bases that Python refuses to build.
  7. Combine isinstance() and issubclass() checks with several parents.

Several parents: the basic rule

A class lists its parents in parentheses, separated by commas. The written base order constrains the C3 MRO; lookup then follows that computed order. For two unrelated bases, the left base appears first. Review single inheritance and overriding for the single-parent case.

Python
class Logger:
    def notify(self):
        return "log"


class Mailer:
    def notify(self):
        return "mail"


class Alert(Logger, Mailer):
    pass


class Alert2(Mailer, Logger):
    pass


print(Alert().notify())     # log
print(Alert2().notify())    # mail
print(Alert.__bases__)
# (<class '__main__.Logger'>, <class '__main__.Mailer'>)

Both parents define notify. Alert finds Logger.notify first because Logger is written first. Alert2 swaps the order and therefore swaps the result. __bases__ keeps the order in which the parents were written.

The same MRO search applies to plain class variables:

Python
class P:
    tag = "P"


class Q:
    tag = "Q"
    extra = 1


class S(P, Q):
    pass


print(S.tag, S.extra, S().tag)   # P 1 P

tag comes from P (first match). extra exists only in Q, so the search continues to it. Nothing is merged; the first class that has the name provides it.

The search order: __mro__

The sequence of classes Python visits is called the method resolution order (MRO). For these ordinary classes, __mro__ stores a tuple starting with the class itself and ending with object. Compare class metadata and introspection to distinguish this from the direct bases:

Python
print([c.__name__ for c in Alert.__mro__])
# ['Alert', 'Logger', 'Mailer', 'object']

The syllabus does not make the exact algorithm an objective, but exam snippets rely on its results, so it is worth knowing the rules it respects:

  1. A class appears before its parents.
  2. The order of the parents in the class statement is preserved.
  3. An ancestor appears after the classes derived from it.
  4. Each base’s existing MRO keeps its relative order in the child: the result is monotonic.

Do not derive a general MRO by a depth-first walk. C3 merges the parent MROs with the written base list. Repeatedly select a list head that occurs in no other remaining list’s tail, append it, and remove it from the list heads. If no head is eligible, class creation fails. The following diamond shows why a shared ancestor is deferred.

The diamond

A diamond occurs when a class inherits from two classes that share a common parent:

Text
      A
     / \
    B   C
     \ /
      D
Python
class A:
    def who(self):
        return "A"


class B(A):
    def who(self):
        return "B"


class C(A):
    def who(self):
        return "C"


class D(B, C):
    pass


print(D().who())                         # B
print([c.__name__ for c in D.__mro__])   # ['D', 'B', 'C', 'A', 'object']

D has no who, so the search follows the MRO: D, then B, which has it. Notice that the MRO is not D, B, A, C: a naive depth-first walk would reach A through B before looking at C. Rule 3 forbids this, because A is also the parent of C, so A must come after both B and C.

This changes the answer when only the second branch overrides the method:

Python
class B2(A):
    pass


class C2(A):
    def who(self):
        return "C2"


class D2(B2, C2):
    pass


print(D2().who())                          # C2
print([c.__name__ for c in D2.__mro__])    # ['D2', 'B2', 'C2', 'A', 'object']

B2 has no who, and with a depth-first walk you would reach A.who and answer "A". The real order checks C2 before A, so the answer is "C2". This is exactly the kind of subtle difference exam questions are built around.

An order Python cannot build

If the left-to-right rule contradicts the rule that a child comes before its parent, class creation fails:

Python
try:
    class T(A, B):      # A listed before its own child B
        pass
except TypeError as e:
    print("TypeError")   # the message starts with: Cannot create a consistent method resolution order

T asks for A before B, but B derives from A, so B must come first. List the more specific class first: class T(B, A).

Mixins: a typical use of several parents

A mixin is a small class that adds one capability and is not meant to be used alone. Placing mixins before the main class lets them take precedence:

Python
import json


class JsonMixin:
    def to_json(self):
        return json.dumps(vars(self), sort_keys=True)


class Item:
    def __init__(self, ref, qty):
        self.ref = ref
        self.qty = qty


class ExportItem(JsonMixin, Item):
    pass


print(ExportItem("A-1", 3).to_json())   # {"qty": 3, "ref": "A-1"}

ExportItem inherits the constructor from Item and the method from JsonMixin. Because the two parents define different names, no conflict exists. The mixin delegates encoding to json.dumps, which produces JSON string quoting. This instance has a dictionary containing only a string and an integer, both directly serializable.

Choosing a specific parent explicitly

The MRO decides the default, but you can bypass it by naming the class. When two parents offer the same method and you need both results, the child overrides the method and calls each parent by name:

Python
class Alert(Logger, Mailer):
    def notify(self):
        return Logger.notify(self) + "&" + Mailer.notify(self)


print(Alert().notify())    # log&mail

Logger.notify(self) fetches the function from the class Logger and passes the object explicitly as self, exactly as in lesson 9.1 where Lamp.switch(l) was equivalent to l.switch(). Lookup starts at the explicitly named class and can still search that class’s bases. Here each named class defines notify directly, so these calls select the stated functions regardless of Alert’s base order. The cost is rigidity: the child must know its parents' names and must be updated if they change. Use this style for a small, stable hierarchy, and super() when the classes are designed to cooperate.

When a snippet seems ambiguous, a good method is to ask three questions in order. First: does the class of the object define the name itself? If yes, that version runs. Second: does the method call a class by name, or use super()? A named lookup starts at that class; super() starts its search after the lexical class in the current object’s MRO, skipping later classes without that method. Third: does the chosen method call another method on self? If so, restart the search from the object's class, as in lesson 10.1.

Constructors with several parents

Constructors deserve special attention. A child with several parents does not call all parent initialisers by itself; you must arrange it.

With explicit parent calls

Python
class Base:
    def __init__(self):
        print("Base")


class L2(Base):
    def __init__(self):
        print("L2")
        Base.__init__(self)


class R2(Base):
    def __init__(self):
        print("R2")
        Base.__init__(self)


class X2(L2, R2):
    def __init__(self):
        L2.__init__(self)
        R2.__init__(self)


X2()

Output:

Text
L2
Base
R2
Base

Each parent is named, so each runs, and Base initialises twice. If Base.__init__ opens a file or increments a counter, the duplicate is a bug.

With super()

super() follows the MRO of the object's class, not simply the parent of the class where it is written. Each class that uses it hands control to the next class in line:

Python
class Base:
    def __init__(self):
        print("Base")


class L(Base):
    def __init__(self):
        print("L start")
        super().__init__()
        print("L end")


class R(Base):
    def __init__(self):
        print("R start")
        super().__init__()
        print("R end")


class X(L, R):
    def __init__(self):
        print("X start")
        super().__init__()
        print("X end")


X()

Output:

Text
X start
L start
R start
Base
R end
L end
X end

The MRO of X is X, L, R, Base, object. In L, super().__init__() does not go to Base; it goes to R, the next class after L in the MRO of the object being built. Then R hands over to Base. Each of X, L, R, and Base runs its initializer once in this example; Base terminates the chain. Cooperative designs require compatible signatures and deliberate delegation. super() alone does not guarantee one call if code delegates repeatedly or also names bases explicitly.

This is the reason super() should be read as "the next class in the MRO" and not "my parent". For a single-parent chain the two readings agree, which is why the difference only appears with diamonds.

When the chain breaks

A super() lookup needs a later provider of the method. This example contrasts a complete composition with one missing that provider:

Python
class Audit:
    def send(self, m):
        return "audit>" + super().send(m)


class Notifier:
    def send(self, m):
        return f"send:{m}"


class Sms(Audit, Notifier):
    pass


class Mix(Audit):
    pass


print(Sms().send("hi"))                       # audit>send:hi
print([c.__name__ for c in Sms.__mro__])      # ['Sms', 'Audit', 'Notifier', 'object']
try:
    Mix().send("x")
except AttributeError as e:
    print("AttributeError")                   # 'super' object has no attribute 'send'

Audit is designed to wrap another class. In Sms the next class after Audit is Notifier, so the call works. Mix has no such class: after Audit comes only object, which has no send, hence AttributeError. The same Audit class behaves differently depending on the class of the object.

Tracing and checking with several parents

Python
print(isinstance(D(), C), issubclass(D, A), D.__bases__)
# True True (<class '__main__.B'>, <class '__main__.C'>)

isinstance and issubclass accept any class in the MRO, so D() is also an instance of B, C, A and object. __bases__ shows only the two direct parents, whereas __mro__ shows the complete chain. When a snippet asks "which classes is this an instance of?", count the MRO; when it asks about __bases__, count only the direct parents.

Tool Result for D of the diamond
D.__bases__ (B, C), the direct parents in written order
D.__mro__ (D, B, C, A, object), the full search order
isinstance(D(), A) True
type(D()) is B False

Worked example: predicting a notification hierarchy

Statement. A system sends messages. Channel returns the text; Audit adds a prefix and delegates with super(); Bracket wraps the text in brackets and also delegates. Two final classes combine them in different orders. Predict the four printed lines.

Python
class Channel:
    def send(self, m):
        return m


class Audit(Channel):
    def send(self, m):
        return "audit:" + super().send(m)


class Bracket(Channel):
    def send(self, m):
        return "[" + super().send(m) + "]"


class Secure(Audit, Bracket):
    pass


class Safe(Bracket, Audit):
    pass


print([c.__name__ for c in Secure.__mro__])
print(Secure().send("go"))
print([c.__name__ for c in Safe.__mro__])
print(Safe().send("go"))

Step 1: the MRO of Secure. Parents are Audit then Bracket; both derive from Channel, which must come after both. The order is Secure, Audit, Bracket, Channel, object.

Step 2: the call in Secure. Audit.send runs first and returns "audit:" + super().send(m). The next class is Bracket, which returns "[" + super().send(m) + "]". The next is Channel, which returns "go". Unwinding: "[go]", then "audit:[go]".

Step 3: the MRO of Safe. Safe, Bracket, Audit, Channel, object.

Step 4: the call in Safe. Bracket.send runs first: "[" + (Audit's result) + "]". Audit returns "audit:go". Final: "[audit:go]".

Text
['Secure', 'Audit', 'Bracket', 'Channel', 'object']
audit:[go]
['Safe', 'Bracket', 'Audit', 'Channel', 'object']
[audit:go]

Why other readings fail. Answering audit:go for the first call treats super() as "the parent Channel" and skips Bracket. Answering [audit:[go]] visits Bracket twice, as if each class called both parents. Listing Channel second in the MRO ignores the rule that a shared ancestor comes after all its children.

Common pitfalls and exam tips

Pitfall What happens Remedy
Ignoring the order of bases Wrong parent's method chosen Read parents left to right, then confirm with the MRO rules
Depth-first walk through a diamond Reaches the shared ancestor too early Remember: shared ancestor after all its children
Reading super() as "my parent" Wrong next class Read it as "next in the MRO of the object"
Explicit calls on both branches of a diamond Shared initialization may run twice Design a cooperative chain with compatible signatures
Listing a parent before its own child TypeError, no consistent MRO Put the more specific class first
Confusing __bases__ and __mro__ Missing or extra classes __bases__ = direct parents, __mro__ = full chain
Forgetting that name clashes are not merged Only the first match is used Expect one provider per name
super() with no class behind it AttributeError Make sure a later class defines the method

Exam tip. Write the MRO first, respecting local base order and each base’s own MRO. In a simple diamond, put the shared ancestor after its descendants. For more complex graphs, use the C3 merge rule instead of a depth-first guess.

Exam tip. If a snippet defines the same method in a grandparent and in the second parent, the second parent usually wins in a diamond.

Exam tip. isinstance(obj, X) is true for every class in the MRO of type(obj).

End-of-lesson case study

Situation. A shop framework has Base with ship() returning "base". Gift(Base) returns "gift+" + super().ship(). Fast(Base) returns "fast+" + super().ship(). A developer defines Order(Gift, Fast) and Rush(Fast, Gift). What do Order().ship() and Rush().ship() return, and what happens with class Bad(Base, Gift)?

Python
class Base:
    def ship(self):
        return "base"


class Gift(Base):
    def ship(self):
        return "gift+" + super().ship()


class Fast(Base):
    def ship(self):
        return "fast+" + super().ship()


class Order(Gift, Fast):
    pass


class Rush(Fast, Gift):
    pass


print(Order().ship())
print(Rush().ship())

Solution, commented. The MRO of Order is Order, Gift, Fast, Base, object, so Gift.ship runs first, delegates to Fast, which delegates to Base: the result is gift+fast+base. For Rush the MRO is Rush, Fast, Gift, Base, object, giving fast+gift+base. The two classes combine the same capabilities, yet the order of the parents changes the visible result.

class Bad(Base, Gift) raises TypeError: Base is listed before its own child Gift, which contradicts the rule that a class appears before its parents. Writing class Bad(Gift, Base) is correct and yields the MRO Bad, Gift, Base, object.

Key terms

  • Multiple inheritance: a class with more than one direct parent.
  • MRO (method resolution order): the sequence of classes searched for attributes, shown by __mro__.
  • Diamond: two classes sharing a common ancestor and combined in a child.
  • Mixin: a small parent class adding one capability, usually listed first.
  • super(): searches after the lexical class in the object’s MRO for the next provider, which can be a sibling.
  • __bases__: the tuple of direct parents in written order.

Summary checklist

  • I can predict which parent's method runs from the order of the bases.
  • I can write the MRO of a class, including a diamond, and follow a call along it.
  • I know a shared ancestor is searched after all the classes that inherit from it.
  • I can explain why class T(A, B) fails when B derives from A.
  • I can trace a super() chain and the order of printed messages.
  • I know explicit parent calls can run a shared ancestor twice.
  • I can tell __bases__ from __mro__ and use isinstance with several parents.

Official sources