Abstraction in Python

Abstraction in Python

In this blog, we are going to have a detailed discussion on the topic ‘Abstraction in Python’. Let’s begin by understanding what abstraction is and how it works in Python.

What is Abstraction in Python?

Abstraction in Python is a process of handling complexity by hiding unnecessary details and showing only the essential information to the user. It is one of the core principles of Object-Oriented Programming (OOP), which allows developers to implement more complex functionality without worrying about the underlying complexity.

Suggested Read: Polymorphism in Python

Abstraction In the Real World

Let’s look at a real-world example to understand the Abstraction. Imagine you are using a social media platform like Facebook. You can easily send messages, share photos, and connect with people. However, you don’t need to know how the platform handles data, manages servers, or performs these operations in the background.

The same concept applies in software development: abstraction allows us to interact with complex systems without the need to understand their intricate details.

Another example: When you use a smartphone, you don’t need to know how its hardware or operating system works. You just use apps, make calls, and browse the internet. This is all abstraction.

This hiding of internal complexity while providing necessary functionality is what we call abstraction.

Importance of Abstraction          

Abstraction helps hide all the irrelevant data/processes of an application to reduce complexity and increase the efficiency of the program.

It makes the code reusable and easier to read and allows for better maintenance in the long run.

Achieving Abstraction in Python

In Python, abstraction can be achieved using Abstract Classes and Abstract Methods. Let’s explore how we can implement this using Python’s built-in abc module.

  • Abstract Method: An abstract method is a method that is declared but contains no implementation. It is just a placeholder that tells the programmer that this method must be overridden by subclasses.
  • Abstract Class: A class containing one or more abstract methods is called an abstract class. You cannot create an instance of an abstract class directly.

Suggested Read: Python init Overview

In Python, the abc module provides the necessary tools to implement abstraction through abstract classes and methods.

from abc import ABC, abstractmethod

class ClassName(ABC):
    @abstractmethod
    def method_name(self):
        pass

Example: Abstraction in Python in Action

Let’s take a practical example of creating an abstract class Shape to represent geometric shapes. We’ll define two concrete subclasses: Rectangle and Circle. Both shapes need to compute their area and perimeter, but the implementation of these methods will differ for each shape.

We will first explain the problem, followed by the solution code to implement it.

Problem:

  • We need a Shape class that requires subclasses to implement two methods: area() and perimeter().
  • Subclasses Rectangle and Circle will implement these methods differently based on their respective formulas.

Solution: Python Code

from abc import ABC, abstractmethod

# Abstract Base Class
class Shape(ABC):
    def __init__(self, shapeType):
        '''Initializes the Shape with a type (e.g., Rectangle, Circle)'''
        self.shapeType = shapeType

    @abstractmethod
    def area(self):
        '''Abstract method to compute the area. To be implemented by subclasses.'''
        pass

    @abstractmethod
    def perimeter(self):
        '''Abstract method to compute the perimeter. To be implemented by subclasses.'''
        pass

# Rectangle class implementing Shape
class Rectangle(Shape):
    def __init__(self, length, breadth):
        '''Initializes Rectangle with length and breadth'''
        super().__init__('Rectangle')
        self.length = length
        self.breadth = breadth

    def area(self):
        '''Computes the area of the Rectangle'''
        return self.length * self.breadth

    def perimeter(self):
        '''Computes the perimeter of the Rectangle'''
        return 2 * (self.length + self.breadth)

# Circle class implementing Shape
class Circle(Shape):
    pi = 3.14

    def __init__(self, radius):
        '''Initializes Circle with radius'''
        super().__init__('Circle')
        self.radius = radius

    def area(self):
        '''Computes the area of the Circle'''
        return round(Circle.pi * (self.radius ** 2), 2)

    def perimeter(self):
        '''Computes the perimeter of the Circle'''
        return round(2 * Circle.pi * self.radius, 2)

Now, let’s see how we can use these classes to create objects of Rectangle and Circle and calculate their areas and perimeters.

Example:

# Creating a Rectangle object with length 30 and breadth 15
rectangle = Rectangle(30, 15)
print(f"Area of Rectangle: {rectangle.area()}")  # 450
print(f"Perimeter of Rectangle: {rectangle.perimeter()}")  # 90

# Creating a Circle object with radius 5
circle = Circle(5)
print(f"Area of Circle: {circle.area()}")  # 78.5
print(f"Perimeter of Circle: {circle.perimeter()}")  # 31.4

Output:

Area of Rectangle: 450
Perimeter of Rectangle: 90
Area of Circle: 78.5
Perimeter of Circle: 31.4

Summary :

Abstraction is an important concept in both the real world and programming. It allows us to hide the complexity of systems and focus only on the essential details. In Python, abstraction is implemented through abstract classes and methods, which make our code cleaner, more manageable, and easier to maintain.

By using abstraction, we can divide the complexity of a program into manageable parts. It also helps us create software that is flexible and adaptable to changes.

Also Read: Python Interview Questions and Answers

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top