Object Oriented Programming in Python

Introduction

In this article, we'll explore the fundamental OOP concepts using classes and objects in Python. Object-Oriented Programming (OOP) is a strong method that helps developers organize code so it's easy to understand, reuse, and maintain. Python is a flexible language that supports OOP concepts well.

1. Classes and Objects

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

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def display_info(self):
        return f"{self.year} {self.make} {self.model}"

# Creating an object
my_car = Car("Toyota", "Corolla", 2022)
print(my_car.display_info())  
# O/P: 2022 Toyota Corolla

In the above example, Car is a class, and my_car is an object (instance) of the Car class.

2. Encapsulation

Encapsulation is the bundling of data and the methods that operate on that data within a single unit (class). It restricts direct access to some of an object's components, which is a means of preventing accidental interference and misuse of the methods and data.

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

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            return True
        return False

    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            return True
        return False

    def get_balance(self):
        return self.__balance

account = BankAccount("123456", 1000)
print(account.get_balance())  # O/P: 1000
account.deposit(500)
print(account.get_balance())  # O/P: 1500

In the above example, account_number and balance are private attributes, accessible only within the class.

3. Inheritance

Inheritance allows a class to inherit attributes and methods from another class. This promotes code reusability and establishes a relationship between parent and child classes.

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

    def start_engine(self):
        return "The engine is running!"

class Car(Vehicle):
    def __init__(self, make, model, fuel_type):
        super().__init__(make, model)
        self.fuel_type = fuel_type

    def honk(self):
        return "Beep beep!"

my_car = Car("Honda", "Civic", "Gasoline")
print(my_car.start_engine())  # O/P: The engine is running!
print(my_car.honk())  # O/P: Beep beep!

In the above example, the Car inherits from the Vehicle and adds its own method honk().

4. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables the use of a single interface with different underlying forms (data types or classes).

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Bhoow!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class Cow(Animal):
    def speak(self):
        return "Moo!"

def animal_sound(animal):
    return animal.speak()

dog = Dog()
cat = Cat()
cow = Cow()

print(animal_sound(dog))  # O/P: Bhoow!
print(animal_sound(cat))  # O/P: Meow!
print(animal_sound(cow))  # O/P: Moo!

In the above example, the animal_sound() function works with any object that has a speak() method, demonstrating polymorphism.

5. Abstraction

Abstraction is the process of hiding the complex implementation details and showing only the necessary features of an object. Abstract classes and methods are used to achieve abstraction in Python.

Summary

Object-oriented programming in Python provides a powerful way to structure code, promoting modularity, reusability, and maintainability. By understanding and applying these core OOP concepts classes and objects, encapsulation, inheritance, polymorphism, and abstraction - you can write more efficient, organized, and scalable Python code.


Similar Articles