Browse by Domains

Abstraction in Python

Table of contents

Abstraction in Python

In this blog, we are going to have a detailed discussion on the topic of Abstraction in Python. So without wasting a second let’s start with the overview of points that we will be discussing further in this module:

  • Introduction
  • Abstraction in Real World
  • Importance
  • Abstract Methods And Classes
  • Working Program for Abstraction in Python
  • Summary

It is going to be an exciting one so let’s go for it. 

Introduction:

What is Abstraction in Python?

Abstraction in python is defined as a process of handling complexity by hiding unnecessary information from the user. This is one of the core concepts of object-oriented programming (OOP) languages. That enables the user to implement even more complex logic on top of the provided abstraction without understanding or even thinking about all the hidden background/back-end complexity.

That’s a very generic core topic not only limited to object-oriented programming. You can observe it everywhere in the real world or in our surroundings.

Abstraction In Real World: 

 For the sake of understanding let us have an example as we all use the social platforms and contact our friends, chat, share images etc., but we don’t know how these operations are happening in the background. Let us take another example, while visiting and reading blogs on the GreatLearning we tend to click on various links and perform various functions unknowingly what is happening in the background. That is exactly the abstraction that works in the OOP.

Importance:                   

         Abstraction provides a programmer to hide all the irrelevant data/process of an application in order to reduce complexity and increase the efficiency of the program. Now, we can start learning how we can achieve abstraction using the Python program.

Achieving Abstraction in Python:

         In Python, abstraction can be achieved by having/using abstract classes and methods in our programs.

Understanding Abstract Methods and Classes:

         An abstract method is a method that is declared, but does not contain implementation. An abstract method in a base class identifies the functionality that should be implemented by all its subclasses. However, since the implementation of an abstract method would differ from one subclass to another, often the method body comprises just a pass statement. Every subclass of the base class will ride this method with its implementation. A class containing abstract methods is called abstract class.Python provides the abc module to use the abstraction in the Python program, syntax as:

from abc import ABC,   
class ClassName(ABC):

Understanding Working program:

To use Python Abstract Base Classes (ABCs), one needs to import ABCMeta and abstractmethod from the abc module. For example,let us examine the class Shape and its subclasses Rectangle and Circle defined in the script shape . Each of the subclasses Rectangle and Circle needs methods for computing area and perimeter. However, the procedure for computing area and perimeter would differ for Rectangle and Circle. Therefore, we define the classes Rectangle and Circle as subclasses of the class Shape. We define methods area and perimeter as abstract methods in the class Shape. The subclasses Rectangle and Circle override the methods area and perimeter by defining their implementation as shown in the program. If the subclasses Rectangle and Circle fail to override any of the methods area or perimeter, Python will yield a TypeError while instantiating them.

from abc import ABCMeta, abstractmethod

class Shape:

    __metaclass__ = ABCMeta 

    def __init__ (self, shapeType):

        ”’Objective: To initialize object of class Shape Input Parameters:

        self (implicit parameter) – object of type Shape

        shapeType – string

        Return Value: None

        ”’

        self.shapeType = shape Type

    @abstractmethod 

    def area(self) :

        pass

    @abstractmethod

    def perimeter (self):

        pass

class Rectangle(Shape):

    def __init__(self, length, breadth):

        ”’Objective: To initialize object of class Rectangle Input Parameters: self (implicit parameter) – object of type Rectangle length, breadth – numeric value 

        Return Value: None ”’

        Shape.__init__(self, ‘Rectangle’)

        self.length = length 

        self.breadth = breadth

    def area (self):

        ”’Objective: To compute area of the Rectangle Input Parameter: 

        self (implicit parameter) object of type Rectangle

        Return Value: numeric value

        ”’

        return self.length * self.breadth

    def perimeter (self):

        return 2 * (self.lenght + self.breadth)

class Circle (Shape):

    pi = 3.14

    def __init__ (self, radius):

        ”’Objective: To initialize object of class Circle Input Parameters: self (implicit parameter) – object of type Circle 

            radius – numeric value 

            Return Value: None”’

        Shape.__init__(self, ‘Circle’)

        self.radius = radius

    def area (self):

        ”’Objective: To compute the area of the Circle

        Input Parameter:

        self (implicit parameter) – object of type Circle 

        Return Value: area – numeric value”’

        return round(Circle.pi * (self.radius ** 2), 2)

    def perimeter(self):

        ”’Objective: To compute the perimeter of the Circle

        Input Parameter:

        self (implicit parameter) – object of type Circle

        Return Value: perimeter – numeric value”’

        return round (2 * Circle.pi * self.radius, 2)

We indicate that a method is abstract by preceding its definition by @abstractmethod (function decorator). Note that the definition of an abstract class begins with

__metaclass__ = ABCMeta

To illustrate the use of abstract classes, we create an object rectangle of the class Rectangle having length and breadth 30 and 15, respectively, and an object circle of the class Circle having radius 5. The methods area and perimeter defined in the subclasses Rectangle and Circle override the corresponding abstract methods defined in the superclass Shape. Next, we see some examples of the use of these methods:

>>> rectangle = Rectangle (30, 15)

>>> rectangle.area ()

450

>>> rectangle.perimeter ()

90 

>>> circle = Circle (5)

>>> circle.area ()

78.5

>>> circle.perimeter ()

31.4

Also Read: Append in Python| How is Append function used in Python

Summary :

Abstraction is a core general topic which you can find in the real world as well as in Object Oriented Programming languages. Any objects in the real world, like your mobile , or classes/methods in your current software project, that hide internal/backend details provide an abstraction.

These abstractions make it easy to handle complexity by dividing them into smaller parts. In the best case, you can use them in the software projects or programs without understanding how they provide the functionality. And that not only helps you to split the complexity of your next software project/programs into manageable parts, it also enables you every morning to brew a fresh cup of amazing coffee while you’re still half asleep.

Also Read: Python Interview Question and Answer 2021

The below path will guide you to become a proficient data scientist.

Data Science Course Certificates
Data Science Course Placements
Data Science Course Syllabus
Data Science Course Eligibility


Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

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

Great Learning Free Online Courses
Scroll to Top