×

Abstraction in Python

What is meant by abstraction generally?

A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but not a detailed overview of the content is known as Abstraction.

What is Abstraction in Python?

The process where the user is exposed only to the outer view but not the detailed structure or functioning of the program is known as Abstraction.

Abstraction can be defined as:

The process of giving access only to certain essential or required details to the user and hiding the unnecessary or unwanted details from the user so that the task that is supposed to be completed is not affected is known as Abstraction.

Abstraction is a process in which the complexity of the problem is hidden, and just the outwork is showcased.

So, let us consider a real-time example that describes abstraction.

Example:

When we play a game on a PC or a mobile phone, we are just aware of the controls, how to play, what makes you score more, what makes you move forward, what makes you move backwards, etc.

We are just allowed to know the game's outer view and the keys or controls required to play the game. We do not know how the game's functioning happens within the program, what program the game consists of, and how the keys are being enabled right after they are addressed.

All these features have been hidden from the user interface so that there will be no duplication and verifying that the main motive of the task is not being disturbed. In the same way, this is the actual process that takes place within a python program while undergoing abstraction.

Let us look forward to the advantages of using abstraction.

Advantages of using Abstraction:

  1. Redundancy or duplication of the programs can be easily avoided.
  2. Provides high security for the program or an application.
  3. No changes can be made in the internal parts of the system program as there will be no allowance or access to the user.
  4. Generates code reusability without any errors.
  5. Code optimization.

Abstraction in python can be implemented in two ways:

  1. By using Abstract class
  2. By using Interface
Abstraction in Python

What is an Abstract Class and an Abstract Method?

Abstract class:

A class defined or declared with at least one Abstract method within its body is known as an Abstract class.

Abstract classes can be used when we want to implement large functions within the body. The subclass inherits the abstract class, and the abstract methods get their definitions in the subclass. This is how the flow of code processing occurs while using abstract classes and abstract methods.

In python, we cannot create an abstract class directly. To use abstract classes, we are supposed to import ABC, i.e., " Abstract Base Class ", from an inbuilt module " abc “.

Abstract Base Classes ( ABC ) :

The classes that act as intermediate classes in order to perform implementations within the other classes are known as " Abstract Base Classes ". It works similarly to the Application Programming Interface ( API ). We use plugins while implementing ABC. We can import Abstract Base Classes from the " abc module ”. We must use ABC to include abstraction in python. A method is said to be an abstract method when declared with the keyword " @abstractmethod ".

The syntax for creating an Abstract class:

from abc import ABC
class ClassName(ABC):
    #statements

Let’s consider an example program:

Example program:

#importing abstract base class from abc module
from abc import ABC, abstractmethod
class Vehicles(ABC):
    @abstractmethod
    def noofwheels(self):
        pass
class Car(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Car: I have 4 wheels")
class Cycle(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Cycle: I have 2 wheels")


class Bike(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Bike: I have 2 wheels")
class Auto(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Auto: I have 3 wheels")
class Truck(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Truck: I have 6 wheels")
obj1 = Car()
obj1.noofwheels()
obj2 = Cycle()
obj2.noofwheels()
obj3 = Bike()
obj3.noofwheels()
obj4 = Auto()
obj4.noofwheels()
obj5 = Truck()
obj5.noofwheels()

Output:

Car: I have 4 wheels
Cycle: I have 2 wheels
Bike: I have 2 wheels
Auto: I have 3 wheels
Truck: I have 6 wheels

Explanation:

Initially, " abstract base class " is imported from the " abc module “. A class    “ Vehicles ” is declared with an abstract method which is represented by  “ @abstractmethod ", and then a common method " noofwheels() ", is declared, which describes the number of wheels that the specified vehicle generally consists of. Thereafter, every class with different vehicles used the abstract method " noofwheels() “ to print separate statements.

The statements have been printed successfully. We've used abstract classes to optimize the code. The code might have been lengthier if the abstract class is not used here.


Related Topics

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

How to Declare a Variable in Python?

The concept of constants and variables is something that we are studying right from our primary classes. We know that constants are the fixed values whereas variables are those whose...

4 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

CatPlot in Python

Python Seaborn Library Seaborn is a superb Python tool for displaying graphical statistics graphing. Seaborn provides different color schemes and attractive default styles to facilitate the creation of various statistics charts...

8 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.

What are the Purposes of Python?

Python is a high-level programming language that is simple to use and easy to write, and Python is a beginner-friendly programming language. A beginner often prefers to start with Python...

6 minutes read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Division in Python

In this tutorial, we will understand what mathematical operation division is and how is it performed in Python Programming language. We will also focus on the operators being used in...

3 minutes read.

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.