Python Tutorial 0/52 lessons ~6 min read Lesson 26
Inheritance & MRO
Python supports multiple inheritance with C3-linearized MRO (Method Resolution Order).
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Python supports multiple inheritance with C3-linearized MRO (Method Resolution Order). Prefer composition; use inheritance for true is-a relationships.
Understanding the topic
Core concepts to understand:
class Dog(Animal):— subclass.super().__init__()calls parent.Cls.__mro__shows resolution order.isinstanceandissubclass.
Syntax reference
Visual flow / code:
python
class Animal:def __init__(self, name): self.name = namedef speak(self): return "..."class Dog(Animal):def speak(self): return "Woof!"class Puppy(Dog):def speak(self):return super().speak() + " (yip!)"p = Puppy("Rex")print(p.speak()) # 'Woof! (yip!)'print(Puppy.__mro__) # MRO chain
Execution workflow
1Inheritance & MRO Workflow
1 / 4class Dog(Animal)
— subclass.
Real-world use
Mixins are a common Python pattern: small classes that add specific behavior (e.g., SerializableMixin, LoggingMixin).
Best practices
- Prefer composition over inheritance.
- Use mixins for cross-cutting behavior.
- Always call
super().__init__.
Common mistakes
- Deep hierarchies → diamond problem; MRO solves it but hierarchies should still stay shallow.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionWhat's MRO?+
Answer
MRO, the Method Resolution Order, is the linear order in which Python searches a class and its bases for an attribute or method. It is computed with the C3 linearization algorithm, which keeps subclasses before bases and respects the order of base classes listed. You can inspect it with
Cls.__mro__ or Cls.mro(), and super() follows it.Follow-up
What does super() actually return?
2IntermediateQuestionComposition vs inheritance?+
Answer
Inheritance models an 'is-a' relationship and couples the subclass to its parent's implementation, while composition models 'has-a' by holding other objects and delegating to them. Composition is usually more flexible and easier to change, so many guidelines say to favor it unless there is a true subtype relationship. Inheritance is still appropriate for real specializations and for frameworks designed to be subclassed.
3IntermediateQuestionWhat are mixins?+
Answer
A mixin is a small class that provides a specific piece of behavior to be combined with other classes through multiple inheritance, and is usually not meant to be instantiated alone. Examples are a
JSONMixin adding to_json. They rely on the MRO and cooperative super() calls, so keep them focused, without conflicting state.Follow-up
What problems can mixins cause?
Summary
In summary: super() + MRO handle multi-inherit. Composition usually wins.
Ready to mark this lesson complete?Track your journey across the entire course.