Abstraction in Python

Abstraction is one of the four fundamental concepts of Object-Oriented Programming (OOP), alongside Encapsulation, Inheritance, and Polymorphism. Abstraction is the process of hiding the internal details and showing only the essential features of an object or a system. It helps to reduce complexity and increase efficiency by allowing programmers to focus on interactions at a higher level.

What is Abstraction?

Abstraction is a way of simplifying complex systems by breaking them down into simpler components. In Python, abstraction is implemented using abstract classes and abstract methods. An abstract class cannot be instantiated, and it can include abstract methods that must be implemented by any subclass that inherits from it.

How to Implement Abstraction in Python?

Python provides the abc module (short for Abstract Base Classes) to define abstract classes and methods. To create an abstract class, you need to:

  1. Import the ABC and abstractmethod from the abc module.
  2. Inherit from the ABC class.
  3. Define abstract methods using the @abstractmethod decorator.

Abstraction in Python


from abc import ABC, abstractmethod

# Abstract class
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

# Subclass implementing the abstract method
class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

# Creating an object of the Rectangle class
rect = Rectangle(4, 5)
print(f"Area of Rectangle: {rect.area()}")  # Output: Area of Rectangle: 20
            

Output

Area of Rectangle: 20

Explanation:

In this example:
  • The Shape class is defined as an abstract class with an abstract method area().
  • The Rectangle class inherits from the Shape class and provides an implementation of the area() method.
  • We created an object of the Rectangle class and called its area() method to calculate the area.

Advantages of Abstraction

Abstraction is a crucial concept in Python that helps in managing complexity in large programs. By focusing on essential features and hiding unnecessary details, abstraction enhances the readability, reusability, and maintainability of your code.