CodeBlanks Logo Icon CodeBlanks

Multiple inheritance

Learn multiple inheritance and MRO.

Multiple inheritance

Multiple inheritance is when a class inherits from more than one parent. Parents are separated by commas in parentheses.

Example: class C(A, B): pass. Here C inherits from both A and B. Methods of both parents are available on a C instance. If a same-name method exists, the MRO order decides.

MRO order

MRO (Method Resolution Order) is the order in which Python searches parents. In multiple inheritance it goes left to right. You can see the order with C.mro().

Example: for class C(A, B) the MRO is [C, A, B, object]. So c.hello() is searched in C first, then A, then B. In diamond inheritance C3 linearization produces a consistent order.

Practice Multiple inheritance C class

Define class A; add def hello(self): and in the body write print("A"). Define class B; add def hello(self): and in the body write print("B"). Then define class C(A, B): pass. Create an instance with c = C() and call c.hello().

Starter code

main.py
# Define the A, B and C classes

Sample solution

main.py
# Define the A, B and C classes
class A:
    def hello(self):
        print("A")

class B:
    def hello(self):
        print("B")

class C(A, B):
    pass

c = C()
c.hello()

Expected output

A

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a multiple inheritance definition?

  • class C: pass
  • class C(A, B): pass Correct answer
  • class C extends A, B: pass
  • class C(A): pass

Explanation: Two parents separated by a comma show multiple inheritance.

2 Complete the multiple inheritance definition

Question
class C(A, ____):
    pass
Answer
class C(A, B):
    pass

Explanation: The second parent is added with a comma.

3 Match the multiple inheritance concepts

Term Meaning
class C(A, B) Multiple inheritance
C.mro() Resolution order
A, B Comma parents

All lessons in Intermediate