In Python Abstract Class class is a class that cannot be instantiated and is meant to serve as a blueprint for other classes.
It defines a common interface and may contain abstract methods, which are methods that have no implementation in the abstract class but must be implemented in its subclasses.
Abstract classes provide a way to define common behavior and enforce certain methods to be implemented by subclasses.
To create an abstract class in Python, you need to make use of the abc
module, which stands for “Abstract Base Classes”. The abc
module provides the ABC
class and the abstractmethod
decorator for defining abstract classes and methods, respectively.
Here’s an example of defining an abstract class in Python:
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def calculate_area(self): pass @abstractmethod def calculate_perimeter(self): pass class Rectangle(Shape): def __init__(self, length, width): self.length = length self.width = width def calculate_area(self): return self.length * self.width def calculate_perimeter(self): return 2 * (self.length + self.width) # Trying to instantiate the abstract class will raise an error # shape = Shape() # Raises TypeError: Can't instantiate abstract class Shape with abstract methods calculate_area, calculate_perimeter # Instantiate the subclass rectangle = Rectangle(5, 3) # Call the overridden methods print(rectangle.calculate_area()) # Output: 15 print(rectangle.calculate_perimeter()) # Output: 16
In the example above, we define an abstract class Shape
that extends the ABC
class from the abc
module. The Shape
class has two abstract methods: calculate_area()
and calculate_perimeter()
. These methods don’t have an implementation in the abstract class but must be implemented in any concrete subclass.
We then define a concrete subclass Rectangle
that inherits from Shape
. The Rectangle
class implements the abstract methods calculate_area()
and calculate_perimeter()
with the appropriate logic for calculating the area and perimeter of a rectangle.
Note that attempting to instantiate the abstract class Shape
directly will raise a TypeError
since abstract classes cannot be instantiated. However, you can create instances of concrete subclasses like Rectangle
that implement the required abstract methods.
Conclusion:
By defining abstract classes, you can enforce certain behavior in subclasses and ensure that specific methods are implemented. This promotes code consistency, modularity, and extensibility in object-oriented programming.