Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Abstract Classes (abc Module) in Python


Abstract classes in Python are classes that cannot be instantiated directly. They are used to define a blueprint for other classes. Abstract classes ensure that derived classes implement certain methods defined in the abstract class. Python provides the abc module to create and manage abstract classes.

What is an Abstract Class?

An abstract class contains one or more abstract methods. An abstract method is a method that is declared but contains no implementation. Subclasses of an abstract class are required to implement all its abstract methods to become instantiable.

Creating Abstract Classes

The abc module provides the ABC class, which stands for "Abstract Base Class." Here's how to define an abstract class:

    from abc import ABC, abstractmethod

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

        @abstractmethod
        def perimeter(self):
            pass
        

Example 1: Implementing Abstract Methods

In this example, we create an abstract class Shape and two concrete classes Rectangle and Circle that implement its abstract methods.

    from abc import ABC, abstractmethod
    import math

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

        @abstractmethod
        def perimeter(self):
            pass

    class Rectangle(Shape):
        def __init__(self, width, height):
            self.width = width
            self.height = height

        def area(self):
            return self.width * self.height

        def perimeter(self):
            return 2 * (self.width + self.height)

    class Circle(Shape):
        def __init__(self, radius):
            self.radius = radius

        def area(self):
            return math.pi * self.radius ** 2

        def perimeter(self):
            return 2 * math.pi * self.radius

    # Example usage
    rectangle = Rectangle(5, 10)
    circle = Circle(7)

    print("Rectangle Area:", rectangle.area())       # Output: 50
    print("Rectangle Perimeter:", rectangle.perimeter()) # Output: 30
    print("Circle Area:", circle.area())             # Output: 153.93804002589985
    print("Circle Perimeter:", circle.perimeter())   # Output: 43.982297150257104
        

Advantages of Abstract Classes

Key Points

Conclusion

Abstract classes in Python, provided by the abc module, are an essential tool for designing consistent and reusable object-oriented programs. By defining abstract methods, they enforce the implementation of required methods in subclasses, ensuring a well-structured and predictable codebase.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java