Python Guide Sidebar

Python – OOPs Concepts

Introduction

Object-Oriented Programming (OOP) is a programming paradigm that organizes code using objects and classes. It helps in structuring programs efficiently, promoting reusability, scalability, and modularity. Python supports OOP principles like encapsulation, inheritance, polymorphism, and abstraction, making it an ideal choice for building real-world applications.

Key OOP Concepts in Python

Python’s OOP approach revolves around the following fundamental concepts:

  1. Classes and Objects
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
  5. Abstraction

Each of these principles ensures better code organization, easier debugging, and enhanced functionality.

1. Classes and Objects

What is a Class?

A class is a blueprint for creating objects. It defines attributes (variables) and behaviors (methods) that an object should have.

class Car:
    def __init__(self, brand, model):
        self.brand = brand  # Attribute
        self.model = model  # Attribute

    def display(self):
        print(f"Car: {self.brand} {self.model}")

# Creating an Object
my_car = Car("Toyota", "Camry")
my_car.display()

What is an Object?

An object is an instance of a class that has its own unique data and behavior.

🔹 Example: my_car is an object of the Car class.

2. Encapsulation

Encapsulation is the bundling of data and methods that operate on the data into a single unit. It restricts direct access to object data to prevent unintended modifications.

Using Private Variables

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private variable

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

# Creating an object
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())  # ✅ Allowed: Access through method
# print(account.__balance)    ❌ Error: Cannot access private variable directly

Benefits of Encapsulation

Protects data from accidental modification
Hides implementation details from the user
Encourages data integrity

3. Inheritance

Inheritance allows one class to derive properties and methods from another, promoting code reuse.

Example of Single Inheritance

class Animal:
    def sound(self):
        print("Animals make sounds.")

class Dog(Animal):  # Inherits from Animal
    def sound(self):
        print("Dogs bark.")

# Creating Objects
obj = Dog()
obj.sound()  # Output: Dogs bark.

Types of Inheritance

  1. Single Inheritance – One class inherits from another.
  2. Multiple Inheritance – A class inherits from multiple classes.
  3. Multilevel Inheritance – A class inherits from a derived class.
  4. Hierarchical Inheritance – Multiple classes inherit from one base class.

4. Polymorphism

Polymorphism allows methods to have different behaviors based on the object calling them.

Method Overriding

class Bird:
    def fly(self):
        print("Birds can fly.")

class Penguin(Bird):
    def fly(self):
        print("Penguins cannot fly.")

# Creating Objects
sparrow = Bird()
penguin = Penguin()

sparrow.fly()  # Output: Birds can fly.
penguin.fly()  # Output: Penguins cannot fly.

Operator Overloading

class Book:
    def __init__(self, pages):
        self.pages = pages

    def __add__(self, other):
        return self.pages + other.pages

book1 = Book(200)
book2 = Book(300)
print(book1 + book2)  # Output: 500

Method Overriding – Subclass modifies a method from the parent class.
Operator Overloading – Redefines how operators work for user-defined classes.

5. Abstraction

Abstraction hides implementation details and exposes only essential features.

Using Abstract Classes

Python provides the abc module to create abstract classes.

from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def start(self):
        pass

class Car(Vehicle):
    def start(self):
        print("Car engine started.")

# car = Vehicle()  ❌ Cannot create an object of an abstract class
obj = Car()
obj.start()  # Output: Car engine started.

Abstract classes in OOP define methods but don’t implement them.
Concrete classes implement the abstract methods.

Advantages of OOP in Python

Modularity – Organizes code into classes and objects.

Reusability – Inheritance reduces redundancy.
Scalability – OOP makes it easier to extend applications.
Data Security – Encapsulation protects data.

Conclusion

Python’s OOP concepts help in designing modular, reusable, and maintainable code. Classes and objects define structure, inheritance allows code reuse, polymorphism enables flexibility, encapsulation ensures security, and abstraction simplifies interfaces. Mastering these principles will help you develop better applications in Python.

Additional Resources