Inheritance &
Method Overriding
Learn how Python classes can inherit attributes and methods from parent classes, and how child classes can override behavior to create specialized objects.
What is Inheritance?
Inheritance is a fundamental concept in object-oriented programming where a new class (called the child or subclass) is created from an existing class (called the parent or superclass). The child class automatically receives all the attributes and methods of the parent.
Why Use Inheritance?
The Class Hierarchy Visualized
The parent class defines the shared structure. Each child class inherits it and can customize specific behavior.
The Inheritance Syntax
What is Method Overriding?
Method overriding occurs when a child class defines a method with the same name as one in its parent class. The child's version replaces the parent's version when called on a child object.
Inheritance vs. Overriding
Calling the Parent with super()
Sometimes you want to extend the parent's method rather than fully replace it. The built-in super() function lets you call the parent's version from inside the child's override.
How to Apply Inheritance
Example 1: Shape Hierarchy
Example 2: Extending with super()
Example 3: Multi-Level Inheritance
Checking Types with isinstance()
The Power of Polymorphism
Because child classes share the same method names as their parents, you can write functions that work with any object in the hierarchy. Python automatically calls the correct overridden version.
Common Mistakes
Summary Comparison
| Inheritance | Overriding | super() | |
|---|---|---|---|
| What it does | Passes all methods to child | Replaces a parent method | Calls the parent version |
| Syntax | class Child(Parent) | Same method name in child | super().method() |
| Purpose | Code reuse | Customization | Extend, not replace |
| Required? | Yes, to build hierarchy | Optional per method | Optional but recommended |
Question 1 of 5
Which syntax correctly makes Cat inherit from Animal?
Question 2 of 5
class Bird: def fly(self): return "Flap flap" class Penguin(Bird): def fly(self): return "I can't fly!"
What does Penguin().fly() return?
Question 3 of 5
What is the purpose of super().__init__() inside a child class's __init__ method?
Question 4 of 5
class Shape: def area(self): return 0 class Circle(Shape): def __init__(self, r): self.r = r c = Circle(5) print(c.area())
What does c.area() return and why?
Question 5 of 5
class Logger: def log(self, msg): return f"[LOG] {msg}" class TimedLogger(Logger): def log(self, msg): base = super().log(msg) return base + " @12:00" print(TimedLogger().log("start"))
What is the output of the code above?