Extending Class Functionality Through Inheritance
Inheritance
is one of the key concepts in Object-Oriented Programming, allowing the reuse and extension of functionality from an existing class to a new class.
By skillfully using inheritance, you can increase code reusability and write maintainable, systematic code.
Parent Class and Child Class
In inheritance, the existing class is called the parent class
(or super class), and the new class that is created from it is called the child class
(or subclass).
A child class can inherit the attributes and methods of a parent class and can also add new attributes or methods, or modify existing ones.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
print(f"Starting the engine of {self.brand} {self.model}")
# Creating the Car class that inherits from Vehicle
class Car(Vehicle):
def __init__(self, brand, model, year):
super().__init__(brand, model) # Calling the parent class constructor
self.year = year
def honk(self):
print(f"{self.brand} {self.model} is honking")
# Creating my_car object
my_car = Car("BrandA", "ModelB", 2024)
# Output: Starting the engine of BrandA ModelB
my_car.start_engine()
# Output: BrandA ModelB is honking
my_car.honk()
Here, the Car
class is created by inheriting from the Vehicle
class.
The Car class uses the functionality of the Vehicle class as is and additionally defines the honk
method.
Why Use Inheritance?
Using inheritance reduces code duplication. Common functionalities can be defined in the parent class and reused in the child class.
For example, when writing classes for various types of vehicles, common functionalities (e.g., starting the engine) can be defined in the parent class, and specific functionalities for each type of vehicle can be defined in the child classes.
Method Overriding
Method Overriding
refers to the process of redefining a method from the parent class in the child class.
When performing method overriding, the method must use the same name as the parent method and include self
.
This allows the child class to redefine the functionality of the parent class to suit itself.
class ElectricCar(Car):
def start_engine(self):
print(f"The electric motor of {self.brand} {self.model} is on")
The ElectricCar
class inherits from the Car
class but overrides the start_engine
method to change the behavior to suit an electric car.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.