Abstraction in Python


Abstraction

Abstraction means hiding the non essential details and showing only essential detail.Abstraction is used to hide the internal functionality of the function from the user. The user only in interact with the basic implementation of the function, but inner working is hidden.

User is familiar with that " what function does" but they do not know "how it does".

In python abstraction is used to hide the irrelevant data in order to reduce the complexity.

In python abstraction can be achieved by using Abstract classes and Interfaces.

Abstract class

A class that consists of one or more abstract method is called the abstract class.

An abstract class can contain the both method normal and abstract method.

An abstract class can not be instantiated. We can not create object for the abstract class.

Unlike the other high level language, Python does not provide the abstract class itself. We need to import the abc module, which provide the base for defining Abstract Base Classes(ABC).

Syntax

from abc import ABC

class class_name(ABC):

Abstract Method

Abstract method do not contain their implementation. Abstract class can be inherited by the subclass and abstract method gets its definition in the subclass.

We use the @abstractmethod decorator to define an abstract method or if we do not provide the definition to the method, it automatically becomes the abstract method.

Example

from abc import ABC,Abstractmethod

class Car(ABC):

        def mileage(self):

                    pass

class Duster(Car):

        def mileage(self):

                    print("The mileage is 18kmph")

class Renault(Car):

        def mileage(self):

                    print("The mileage is 20kmph")

class Suzuki(Car):

        def mileage(self):

                    print("The mileage is 25kmph")

r=Renault()

r.mileage()

d=Duster()

d.mileage

s=Suzuki()

s.mileage()

Output

The mileage is 20kmph

The mileage is 18kmph

The mileage is 25kmph





No comments:

Post a Comment