Inheritance
Single Inheritance
Inheriting from one parent class and extending behavior
Interview: Fundamental OOP — tests understanding of is-a relationships, method overriding, and the Liskov Substitution Principle
Single inheritance is the simplest form of inheritance where a class (child/subclass) inherits from exactly one parent (superclass). The child class gets all attributes and methods of the parent, and can override or extend them. This creates an "is-a" relationship — a Dog is an Animal.
How Inheritance Works
- The child class inherits all public/protected attributes and methods
- The child can override methods to change behavior
- The child can extend methods using
super() - Python uses the MRO (Method Resolution Order) to find methods
- All classes implicitly inherit from
object
Liskov Substitution Principle (LSP)
A key design principle: if class B inherits from class A, you should be able to use B anywhere A is expected without breaking the program. Violating LSP often means your inheritance hierarchy is wrong.
Checking Inheritance
Use isinstance(obj, Class) to check if an object is an instance of a class (or its subclasses). Use issubclass(Child, Parent) to check class relationships.
Interview Tip
Prefer composition over inheritance when the relationship is "has-a" rather than "is-a". Interviewers love asking when inheritance is inappropriate.
Use Cases
Creating specialized types from general base classes (Dog from Animal)
Framework extension: custom handlers inheriting from base handler
UI components: Button inheriting from Widget
Template method pattern: parent defines algorithm, children override steps
Plugin architectures: plugins inherit from base plugin class
Common Mistakes
Forgetting to call super().__init__() — parent attributes not initialized
Inheritance for code reuse when composition would be better (wrong "is-a" relationship)
Violating Liskov Substitution Principle — child changes parent behavior unexpectedly
Deep inheritance hierarchies (prefer shallow hierarchies with composition)
Not using NotImplementedError in abstract methods to enforce overriding