2.2.1 Inheritance
Inheritance (Python OOP)
Inheritance lets you create a new class based on an existing class.
- The existing class is the parent (or base) class.
- The new class is the child (or derived) class.
The child class automatically gets the parent’s attributes and methods, and can add or modify behavior.
Why Use Inheritance?
- Avoid repeating code (DRY: Don’t Repeat Yourself)
- Model real relationships (a
Caris aVehicle) - Extend features safely without rewriting everything
Example 1: Vehicle -> Car and Bike
PYTHON
class Vehicle:
def __init__(self, brand):
self.brand = brand
def start(self):
return f"{self.brand} vehicle started"
class Car(Vehicle):
def __init__(self, brand, doors):
super().__init__(brand)
self.doors = doors
def honk(self):
return "Beep beep!"
class Bike(Vehicle):
def ring_bell(self):
return "Ring ring!"
car = Car("Toyota", doors=4)
bike = Bike("Giant")
print(car.start())
print(car.honk())
print(bike.start())
print(bike.ring_bell())
What to notice:
CarandBikereusestart()fromVehicle.Caraddsdoorsandhonk().Bikeaddsring_bell().
Example 2: Overriding (Changing Parent Behavior)
PYTHON
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
animals = [Dog(), Cat()]
for a in animals:
print(a.speak())
Dog and Cat override the parent’s speak().
super() (Calling the Parent)
Use super() when you still want the parent logic.
PYTHON
class User:
def __init__(self, username):
self.username = username
class Admin(User):
def __init__(self, username, permissions):
super().__init__(username)
self.permissions = permissions
admin = Admin("root", permissions=["read", "write", "delete"])
print(admin.username, admin.permissions)
When NOT to Use Inheritance (Beginner Rule)
Don’t force inheritance just to reuse a few lines.
- If the relationship is not “is-a” (Car is a Vehicle), inheritance may be wrong.
- Sometimes composition is better: “has-a” (Car has an Engine).
Quick Practice
Make a base class Employee with:
name- method
get_salary()
Create two child classes:
FullTimeEmployee(fixed monthly salary)PartTimeEmployee(hourly_rate * hours)
Call get_salary() for both.