Abstraction

Abstraction

ยท

2 min read

  • Abstraction allows you to create abstract classes and methods to represent common characteristics and behaviors of a group of related objects.

  • It focuses on hiding the internal implementation details of a class and providing a simplified interface for interacting with objects.

  • In Python, abstraction is achieved through abstract classes and methods using the abc module, which stands for "Abstract Base Classes".

Abstract Classes

  • An abstract class is a class that cannot be instantiated and acts as a blueprint for creating subclasses.

  • It is a common interface or application programming interface(API) for concrete subclass.

from abc import ABC, abstractmethod

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

obj = Shape()
obj.area()

Output

TypeError: Can't instantiate abstract class pen with abstract method area

In this example, Shape is an abstract class that defines an abstract methodarea(). The abstractmethod decorator indicates that these methods must be implemented in the child subclasses derived from the Shape class. Attempting to create an instance of the Shape class directly will result in a TypeError.

from abc import ABC, abstractmethod

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

class Circle(Shape):
    pass

obj = Circle()

Output

TypeError: Can't instantiate abstract class pen with abstract method area

If I implement the radius() method in the child class then it executes with error-free


from abc import ABC, abstractmethod

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

'''
Circle class inherit abstract class Shape ,so it is mandatory to use 
method of parent/abstract class in this child class
'''
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius**2


obj = Circle(2)
area = obj.area()
print(f"Area is : {area}")

Output :

Area is : 12.56

In this example, the Circle class is a subclass of the Shape abstract class. It provides implementations for the area() and perimeter() methods, which are required by the Shape abstract class. The Circle class can be instantiated, and its methods can be called to perform specific calculations related to circles.

ย