How to Use abstractmethod in Python

Define an abstract base class with abstract methods to enforce a common interface across subclasses.

Medium Python 3.4+ Aug 9, 2026 OOP & classes 10 views 0 copies

Python code

42 lines
Python 3.4+
import 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

stdout
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

  1. Use `@abc.abstractmethod` on a property with `@property` for abstract attributes.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.