Abstract classes in Python provide a powerful way to define interfaces and ensure consistent behavior across related classes. They serve as blueprints for other classes, enforcing a common structure while allowing for flexible implementation.
An abstract class is a class that cannot be instantiated directly and is designed to be subclassed. It may contain abstract methods (methods without implementation) that must be implemented by its subclasses. Abstract classes are useful for defining a common interface for a group of related classes.
Python uses the abc
module to create abstract base classes. Here's how you can define an abstract class:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
In this example, Shape
is an abstract base class with two abstract methods: area()
and perimeter()
.
To use an abstract class, you need to create a concrete subclass that implements all the abstract methods. Here's an example:
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)
# Creating an instance
rect = Rectangle(5, 3)
print(f"Area: {rect.area()}")
print(f"Perimeter: {rect.perimeter()}")
To deepen your understanding of abstract classes and object-oriented programming in Python, explore these related topics:
By mastering abstract classes, you'll be able to design more robust and flexible Python programs, especially when working on large-scale projects or creating frameworks for others to use.