Imagine a family where children inherit traits from their parents. In Python, inheritance works similarly—one class can inherit attributes and methods from another.
This means we don’t have to rewrite common features. Instead, we create a parent class, and new classes (children) can build upon it, saving time and making the code more efficient.
💡 Analogy: Inheritance is like hand-me-down clothes—new generations (child classes) inherit features from the old ones (parent class) but can still make modifications.
By the end of this lesson, you will be able to:
Understand inheritance in OOP.
Create child classes that inherit from parent classes.
Override methods in a child class.
Inheritance – A mechanism that allows a child class to inherit attributes and methods from a parent class.
Parent class – The base class that provides attributes and methods to other classes.
Child class – A class that inherits from another class, extending its functionality.
super() function – Calls the constructor of the parent class inside a child class.
Method overriding – Redefining a method in a child class to change its behavior.
Example 1: Creating a Parent and Child Class
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model)
self.doors = doors
car1 = Car("Toyota", "Corolla", 4)
print(car1.brand) # Output: Toyota
Forgetting to use super() to inherit attributes from the parent class.
Redefining a method without calling the parent version when needed.
🔗 Practice on W3Schools: Inheritance – Learn how to create and use child classes in Python.
🔗 Try It Online: Run Your Code Here – Test your Python code instantly.
1️⃣ Basic Challenge:
Create a Vehicle class with brand and model attributes, then create an instance of the class.
2️⃣ Extended Challenge:
Create a Car class that inherits from Vehicle and adds a doors attribute.
3️⃣ Advanced Challenge:
Write a program that creates a parent class Animal with a speak() method, then creates Dog and Cat child classes that override speak().
Write the example from this lesson, ensuring you include:
✅ A parent class with attributes
✅ A child class inheriting from the parent
✅ Using super() to call the parent constructor
Read the example code before writing!