How to Use abstractmethod in Python
Define an abstract base class with abstract methods to enforce a common interface across subclasses.
Python code
42 linesimport abc
class Shape(abc.ABC):
@abc.abstractmethod
def area(self):
"""Calculate area of the shape."""
@abc.abstractmethod
def perimeter(self):
"""Calculate perimeter of the shape."""
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 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
if __name__ == "__main__":
rect = Rectangle(5, 3)
circle = Circle(4)
shapes = [rect, circle]
for shape in shapes:
print(f"{type(shape).__name__}: area={shape.area():.2f}, perimeter={shape.perimeter():.2f}")
try:
incomplete = Shape()
except TypeError as e:
print(f"Error creating Shape: {e}")
Output
Rectangle: area=15.00, perimeter=16.00
Circle: area=50.27, perimeter=25.13
Error creating Shape: Can't instantiate abstract class Shape with abstract method area
How it works
The abc.ABC class marks Shape as abstract, and @abc.abstractmethod declares methods that must be overridden. Subclasses like Rectangle and Circle implement these methods, making them concrete and instantiable. Attempting to create an instance of Shape raises a TypeError because it is abstract. The abc module is part of the standard library, so no extra dependencies are required.
Common mistakes
- Forgetting to inherit from `abc.ABC` or use `metaclass=abc.ABCMeta`.
- Not implementing all abstract methods in subclasses, causing instantiation errors.
- Leaving an abstract method body empty without the decorator, so it is not enforced.
Variations
- Use `@abc.abstractmethod` on a property with `@property` for abstract attributes.
- Use `@classmethod` or `@staticmethod` with `@abc.abstractmethod` for abstract class methods.
Real-world use cases
- Defining a base `PaymentGateway` class where every provider must implement `charge()` and `refund()`.
- Creating a `Database` interface that MySQL and PostgreSQL adapters both fulfill.
- Designing a `Report` base with `generate()` and `save()` so each format implements its own logic.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.