Python24 min read

Python Abstract Base Classes

Use ABCs to design clean interfaces, enforce required methods, and build maintainable code for teams and large projects.

David Miller
August 14, 2025
12.5k397

Abstract Base Classes (ABCs) help you define an interface.

      If you are building a project with a team, ABCs are very useful because they:
      - enforce a contract
      - prevent incomplete classes
      - make code easier to maintain
      
      ## Basic ABC example
      
      ```python
      from abc import ABC, abstractmethod
      
      class Animal(ABC):
          @abstractmethod
          def speak(self):
              pass
      
          @abstractmethod
          def move(self):
              pass
      
      class Dog(Animal):
          def speak(self):
              return "Woof!"
      
          def move(self):
              return "Running"
      
      d = Dog()
      print(d.speak())
      print(d.move())
      ```
      
      Trying to instantiate Animal will fail.
      
      ## ABC with abstract properties
      
      ```python
      from abc import ABC, abstractmethod
      
      class Shape(ABC):
          @property
          @abstractmethod
          def area(self):
              pass
      
      class Rectangle(Shape):
          def __init__(self, w, h):
              self.w = w
              self.h = h
      
          @property
          def area(self):
              return self.w * self.h
      
      r = Rectangle(10, 20)
      print(r.area)
      ```
      
      ## Real-world example: database interface
      
      ```python
      from abc import ABC, abstractmethod
      
      class Database(ABC):
          @abstractmethod
          def connect(self):
              pass
      
          @abstractmethod
          def query(self, sql):
              pass
      
          @abstractmethod
          def close(self):
              pass
      
      class PostgreSQL(Database):
          def connect(self):
              print("Connected")
      
          def query(self, sql):
              print("Running:", sql)
      
          def close(self):
              print("Closed")
      
      db = PostgreSQL()
      db.connect()
      db.query("SELECT * FROM users")
      db.close()
      ```
      
      ## Graph: contract enforcement
      
      ```mermaid
      flowchart LR
        A[ABC Interface] --> B[Concrete class must implement]
        B --> C[Implementation exists]
        C --> D[Safe to use in codebase]
      ```
      
      ## Key points
      
      - ABC enforces required methods
      - Useful for big projects and team work
      - Prevents incomplete implementations
      
#Python#Advanced#OOP