Member-only story
Day 16 of #100DaysOfCode in Python: Dive into Inheritance and Polymorphism in OOP
Welcome to Day 16 of the #100DaysOfCode challenge in Python! Today, we are delving deeper into the core concepts of Object-Oriented Programming (OOP): inheritance and polymorphism. These essential elements empower you to create more organized, reusable, and efficient code. Let’s take a closer look!
Inheritance
Inheritance is one of the four pillars of OOP. It allows a class, known as the subclass, to inherit attributes and methods from another class, referred to as the superclass. This mechanism promotes code reusability and establishes a natural hierarchy between classes.
Creating Subclasses
Consider a superclass Vehicle
with general attributes like make
, model
, and year
. You can create a subclass Car
that inherits these attributes while also introducing specific features like seating_capacity
and fuel_type
.
class Vehicle:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
class Car(Vehicle):
def __init__(self, make, model, year, seating_capacity, fuel_type):
super().__init__(make, model, year)
self.seating_capacity = seating_capacity
self.fuel_type = fuel_type