Python Abstract Class with Concrete Subclasses

Define an abstract base class with abstract methods and implement them in concrete subclasses like Rectangle and Circle.

Medium Python 3.9+ Aug 9, 2026 OOP & classes 14 views 0 copies

Python code

40 lines
Python 3.9+
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

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)
    print(f"Rectangle area: {rect.area()}")
    print(f"Rectangle perimeter: {rect.perimeter()}")

    circle = Circle(4)
    print(f"Circle area: {circle.area():.2f}")
    print(f"Circle perimeter: {circle.perimeter():.2f}")

Output

stdout
Rectangle area: 15
Rectangle perimeter: 16
Circle area: 50.27
Circle perimeter: 25.13

How it works

The ABC class from the abc module marks a class as abstract. Methods decorated with @abstractmethod must be overridden in any concrete subclass. Attempting to instantiate Shape directly raises a TypeError, enforcing the contract. Each subclass provides its own implementation of area and perimeter, so callers can treat all shapes uniformly.

Common mistakes

  • Forgetting to inherit from ABC or missing @abstractmethod decorator
  • Trying to instantiate the abstract class directly
  • Forgetting to implement all abstract methods in the subclass

Variations

  1. Use `@property` on abstract methods to require read-only attributes.
  2. Use dataclasses for subclasses to reduce boilerplate.

Real-world use cases

  • Define a common interface for payment processors (e.g., charge, refund) enforced across providers.
  • Build a plugin system where each plugin must implement required hooks.
  • Model geometric shapes for a rendering engine that needs a uniform area calculation interface.

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.