In this blog, I will discuss Object-Oriented programming concept using python. OOPs is a programming paradigm which is centered around the classes and objects. classes serve as blueprints that encapsulates data (attributes) and functions (methods) and objects on the other side is an instance of these classes, it represents specific data or real-world entity. Simply put, OOP provides a set of principles that help us solve real-world problems effectively. Python, as a programming language, is designed with these concepts at its core, making it a powerful tool for developers.
Main concepts in Object-Oriented Programming,
Classes
Object
Encapsulation
Inheritance
Abstraction
Polymorphism
Classes
Classes are blueprints for creating objects, containing data (attributes) and functions (methods). With the help of classes, objects being created.
For example, consider a scenario where we need to organize the information about cars based on their properties. Such as, brand, manufactured date, ownership of the cars, how much it cost etc. Which helps customers to choose their desired car, and which simplifies the process of purchasing. To achieve this, we need a blueprint which consists of all the data and functionality of the cars. That blueprint is nothing but class
it has all the data like, brand, manufacturing date, price etc, and as well functions, like how the engine works, EMI calculations, privacy policies etc. Using this class, we can create objects representing individual cars with specific properties and behaviors.
# Define the Car class
class Car:
def __init__(self, brand, manufacturing_date, price):
self.brand = brand
self.manufacturing_date = manufacturing_date
self.price = price
# Method to display car details
def display_details(self):
return f"Brand: {self.brand}, Manufactured on: {self.manufacturing_date}, Price: ${self.price}"
Objects
Objects are the instances of these classes which represent specific data or real-world entity.
For example, Consider the last scenario where we created blueprint for the car, creating an object represents particular car with its brand, manufacturing date and price.
# Create car objects
car1 = Car("Toyota", "2022-01-15", 25000)
car2 = Car("Tesla", "2023-05-20", 60000)
# Display car details
print(car1.display_details())
print(car2.display_details())
Encapsulation
Encapsulation is the concept of hiding internal details of an object to restrict direct access by users. It ensures that critical data and methods are not directly exposed, reducing the risk of unauthorized modifications and data breaches. By using encapsulation, we can protect the core functionality of an object and control how it is accessed and modified through well-defined interfaces
For example, in the case of cars, encapsulation can be thought of as hiding how the engine works. Just like the front hood of a car is locked and only accessible to a mechanic, encapsulation ensures that users can't directly modify critical internal mechanisms. This helps maintain the car's integrity and prevents accidental or unauthorized changes.
class Car:
def __init__(self, brand):
self.brand = brand
self.__engine_status = "Off" # Private attribute
# Public method to start the engine
def start_engine(self):
self.__engine_status = "On"
return "Engine started."
# Public method to stop the engine
def stop_engine(self):
self.__engine_status = "Off"
return "Engine stopped."
# Private method (cannot be accessed directly)
def __check_engine(self):
return f"Engine is currently {self.__engine_status}."
# Public method to get engine status
def get_engine_status(self):
return self.__check_engine()
# Create a car object
car = Car("Toyota")
# Start the engine
print(car.start_engine())
# Get engine status
print(car.get_engine_status())
# Attempting to access private attribute or method directly will result in an error
# print(car.__engine_status) # This will raise an AttributeError
Inheritance
Inheritance is a sub-class inheriting all the properties of its super class. Generally, they are called as child and parent class. where child class inherit all the data and functions from its parent class and may also include extra features.
For example, in the case of cars, they can be considered a subclass of the class Vehicle
. Cars inherit all the properties of Vehicle
, which means they share common characteristics like wheels, fuel type, or capacity while adding specific features unique to cars.
# Base class
class Vehicle:
def __init__(self, vehicle_type, fuel_type):
self.vehicle_type = vehicle_type
self.fuel_type = fuel_type
def display_info(self):
return f"Vehicle Type: {self.vehicle_type}, Fuel Type: {self.fuel_type}"
# Subclass
class Car(Vehicle):
def __init__(self, brand, model, fuel_type):
super().__init__("Car", fuel_type) # Inherit from Vehicle
self.brand = brand
self.model = model
def display_car_info(self):
return f"Brand: {self.brand}, Model: {self.model}, {super().display_info()}"
# Create an object of Car
car = Car("Toyota", "Camry", "Petrol")
# Display car details
print(car.display_car_info())
Abstraction
Abstraction is the process of hiding the internal implementation details of an object and exposing only the necessary functionalities. It focuses on what an object does rather than how it does it.
For example, we just need to know how to use steering, clutch, break in the car without worrying about how it has implemented internally.
from abc import ABC, abstractmethod
# Abstract class
class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass
# Subclass
class Car(Vehicle):
def start_engine(self):
return "Car engine started."
# Create an object of Car
my_car = Car()
print(my_car.start_engine())
Polymorphism
Polymorphism is an OOP concept that allows objects of different classes to be treated as objects of a common superclass. It enables methods to be used interchangeably, allowing different classes to have methods with the same name but potentially different implementations.
For example, polymorphism allows methods with the same name to behave differently based on the object calling them. In the car example, both Car
and Bike
classes implement start_engine()
in their own way, but we can call the method on both objects using the same function.
# Base class
class Vehicle:
def start_engine(self):
pass
# Subclass 1
class Car(Vehicle):
def start_engine(self):
return "Car engine started."
# Subclass 2
class Bike(Vehicle):
def start_engine(self):
return "Bike engine started."
# Polymorphism: Using the same method name on different objects
def start_vehicle_engine(vehicle: Vehicle):
print(vehicle.start_engine())
# Create objects
car = Car()
bike = Bike()
# Calling the same method on different objects
start_vehicle_engine(car)
start_vehicle_engine(bike)
Conclusion
In conclusion, object-oriented programming (OOP) helps us organize and structure our code more efficiently. Concepts like encapsulation, inheritance, abstraction, and polymorphism allow us to create flexible, reusable, and easy-to-understand programs. By applying these principles, we can model real-world problems effectively and improve code maintenance.