Inheritance
Multiple Inheritance
Inheriting from multiple parent classes and the diamond problem
Interview: Advanced OOP — tests understanding of MRO, diamond problem, and when multiple inheritance is appropriate
Multiple inheritance allows a class to inherit from more than one parent class. While powerful, it introduces complexity like the diamond problem. Python resolves method conflicts using the C3 linearization algorithm (MRO). Use multiple inheritance carefully — mixins are the safest use case.
The Diamond Problem
When two parent classes share a common ancestor, and the child inherits from both parents, which ancestor method should be called? Python's MRO resolves this using C3 linearization, ensuring a consistent, predictable order.
Best Practices
- Use mixins — small, focused classes that add specific functionality
- Keep inheritance hierarchies shallow
- Always use
super()to call parent methods (ensures MRO is followed) - Avoid inheriting from classes that weren't designed for multiple inheritance
- Consider composition or protocols as alternatives
Common Pitfall
The order of parent classes matters! class D(B, C) is different from class D(C, B). Python searches left to right, so B's methods take precedence over C's.
Use Cases
Adding serialization (JSON, XML) to any class via mixins
Logging capabilities across unrelated class hierarchies
GUI frameworks: combining draggable, resizable, closable behaviors
Django class-based views: LoginRequiredMixin, PermissionRequiredMixin
Adding comparison behavior (ComparableMixin) to custom classes
Common Mistakes
Inheriting from parents in wrong order — affects method resolution
Creating complex diamond hierarchies that are hard to reason about
Not using super() in all methods — breaks MRO chain
Using multiple inheritance when composition would be simpler
Mixins that depend on methods/attributes not guaranteed to exist