Python OOPs Concepts – Real-World Examples

Introduction

Object-Oriented Programming (OOP) uses real-world entities as models for programming, which makes it easier to understand and design complex systems. In the previous chapter, we learned about basics of Python OOPs. In this chapter, we will learn each OOP concept with real-world examples.

1. Class and Object

A class is a blueprint for creating objects. It defines a set of attributes and methods that the created objects will have.

An object is an instance of a class. It is a concrete entity based on the class blueprint that holds real values for the attributes defined by the class.

Example: School System

Class and Object

A Student class can represent a student in a school. Each student has attributes like name and roll_number and methods like display_details.

class Student:
    def __init__(self, name, roll_number):
        self.name = name
        self.roll_number = roll_number

    def display_details(self):
        print(f"Name: {self.name}, Roll Number: {self.roll_number}")

# Creating objects of the Student class
student1 = Student("Ramesh", 101)
student2 = Student("Sita", 102)

# Accessing attributes and methods
student1.display_details()  # Output: Name: Ramesh, Roll Number: 101
student2.display_details()  # Output: Name: Sita, Roll Number: 102

2. Encapsulation

Encapsulation is the principle of bundling data (attributes) and methods that operate on the data into a single unit (class) and restricting direct access to some of the object’s components. This can prevent the accidental modification of data.

Example: Bank Account

Encapsulation

A BankAccount class encapsulates the account details and provides methods to access and modify the balance securely.

class BankAccount:
    def __init__(self, account_number, balance):
        self.__account_number = account_number  # Private attribute
        self.__balance = balance  # Private attribute

    def get_balance(self):
        return self.__balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
        else:
            print("Invalid amount")

    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Invalid amount or insufficient balance")

# Creating an object of the BankAccount class
account = BankAccount("1234567890", 10000)

# Accessing and modifying balance using methods
print(account.get_balance())  # Output: 10000
account.deposit(5000)
print(account.get_balance())  # Output: 15000
account.withdraw(3000)
print(account.get_balance())  # Output: 12000

3. Inheritance

Inheritance is a way to create a new class (derived class) from an existing class (base class). The derived class inherits the attributes and methods of the base class and can also have additional attributes and methods.

Example: Vehicle System

Inheritance

A Vehicle class can be a base class with common attributes and methods, and specific vehicle types like Car and Bike can inherit from it.

class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display_info(self):
        return f"Brand: {self.brand}, Model: {self.model}"

class Car(Vehicle):
    def __init__(self, brand, model, seating_capacity):
        super().__init__(brand, model)
        self.seating_capacity = seating_capacity

    def display_info(self):
        return f"Car -> {super().display_info()}, Seating Capacity: {self.seating_capacity}"

class Bike(Vehicle):
    def __init__(self, brand, model, type):
        super().__init__(brand, model)
        self.type = type

    def display_info(self):
        return f"Bike -> {super().display_info()}, Type: {self.type}"

# Creating objects of derived classes
car = Car("Tata", "Nexon", 5)
bike = Bike("Bajaj", "Pulsar", "Sport")

# Accessing inherited and overridden methods
print(car.display_info())  # Output: Car -> Brand: Tata, Model: Nexon, Seating Capacity: 5
print(bike.display_info()) # Output: Bike -> Brand: Bajaj, Model: Pulsar, Type: Sport

4. Polymorphism

Polymorphism means “many shapes” and allows methods to do different things based on the object it is acting upon. It allows you to define methods in the derived class with the same name as in the base class.

Example: Payment System

Polymorphism

A Payment system can use different payment methods like CreditCard and DebitCard, both implementing a common pay method.

class Payment:
    def pay(self, amount):
        pass

class CreditCard(Payment):
    def pay(self, amount):
        return f"Paid {amount} using Credit Card"

class DebitCard(Payment):
    def pay(self, amount):
        return f"Paid {amount} using Debit Card"

# Function that uses polymorphism
def process_payment(payment_method, amount):
    print(payment_method.pay(amount))

# Using different payment methods
credit_card_payment = CreditCard()
debit_card_payment = DebitCard()

process_payment(credit_card_payment, 1000)  # Output: Paid 1000 using Credit Card
process_payment(debit_card_payment, 2000)   # Output: Paid 2000 using Debit Card

5. Abstraction

Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object. In Python, this is achieved through abstract classes and methods.

Example: Employee System

Abstraction

An Employee class can be an abstract class with a method calculate_salary, and specific types of employees like FullTimeEmployee and PartTimeEmployee can implement this method.

from abc import ABC, abstractmethod

class Employee(ABC):
    @abstractmethod
    def calculate_salary(self):
        pass

class FullTimeEmployee(Employee):
    def __init__(self, name, monthly_salary):
        self.name = name
        self.monthly_salary = monthly_salary

    def calculate_salary(self):
        return self.monthly_salary

class PartTimeEmployee(Employee):
    def __init__(self, name, hourly_rate, hours_worked):
        self.name = name
        self.hourly_rate = hourly_rate
        self.hours_worked = hours_worked

    def calculate_salary(self):
        return self.hourly_rate * self.hours_worked

# Creating objects of derived classes
full_time = FullTimeEmployee("Ramesh", 50000)
part_time = PartTimeEmployee("Sita", 200, 120)

# Accessing abstract method
print(f"Full-time employee salary: {full_time.calculate_salary()}")  # Output: Full-time employee salary: 50000
print(f"Part-time employee salary: {part_time.calculate_salary()}")  # Output: Part-time employee salary: 24000

Conclusion

These real-world examples demonstrate how the core concepts of OOP (Class and Object, Encapsulation, Inheritance, Polymorphism, and Abstraction) can be applied to model complex systems. By understanding and implementing these concepts, you can create robust, maintainable, and scalable software solutions.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top