Abstract Base Classes
About
An Abstract Base Class (ABC) in Python is a class that defines a blueprint for other classes. It is not intended to be instantiated directly but instead serves as a base class for other classes. Abstract Base Classes define methods that must be implemented by any concrete (non-abstract) subclass, ensuring that subclasses adhere to a specific interface or contract
Python provides abc
module to implement ABC
Key Principles
-
Cannot Be Instantiated
We cannot create objects of an abstract class. It is only used as a blueprint for other classes
-
Abstract Methods
A method declared in an ABC that has no implementation in the ABC itself. Subclasses must override and implement these methods
-
Optional Concrete Methods
ABCs can also define concrete methods (methods with implementations) that can be inherited by subclasses
-
Ensures Interface Compliance
ABCs ensure that all subclasses implement the required methods, providing a form of compile-time check in Python's dynamic environment
Example
from abc import ABC, abstractmethod
# Define an abstract base class
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
# Concrete subclass must implement the abstract methods
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)
# Instantiate concrete subclass
rect = Rectangle(10, 5)
print(f"Area: {rect.area()}") # Area: 50
print(f"Perimeter: {rect.perimeter()}") # Perimeter: 30
print(isinstance(rect, Shape)) # True
print(issubclass(Rectangle, Shape)) # True
Use Cases
- Interface Enforcement
- Improved Design
- Polymorphism
Pros
- Encapsulation of Contracts
- Code maintainability
- Error Prevention