Abstract Base Classes (ABCs) in Python provide a way to define interfaces for other classes. They allow you to specify methods that must be implemented in any subclass, promoting a consistent interface across different implementations.
Python provides the abc module, which facilitates the creation of abstract base classes.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
Subclasses of Shape must implement the abstract methods area and perimeter.
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
def print_shape_info(shape: Shape):
print(f"Area: {shape.area()}")
print(f"Perimeter: {shape.perimeter()}")
# Instances
circle = Circle(5)
square = Square(4)
print_shape_info(circle)
# Output:
# Area: 78.5
# Perimeter: 31.400000000000002
print_shape_info(square)
# Output:
# Area: 16
# Perimeter: 16
Abstract Base Classes in Python are a powerful tool for defining consistent interfaces and organizing code. They help enforce method implementations in subclasses, promoting code reusability and maintainability.