Skip to content

Module 11 · Object-Oriented Programming — topic 22 of 25

Abstract classes

Formal interfaces with the abc module: ABC and @abstractmethod, why abstract classes can't be instantiated, concrete methods in abstract classes, and enforcing that subclasses implement required methods.

Beginner 10 min read·Lesson 179 of 306 in Python Programming

Learning objectives

  • Create abstract base classes with ABC and @abstractmethod
  • Explain the error when instantiating an abstract class
  • Combine abstract and concrete methods

Definition

An abstract class is a class that cannot be instantiated and exists to be subclassed. In Python you create one by inheriting from abc.ABC and marking required methods with @abstractmethod; a subclass can be instantiated only when it implements all of them.

Introduction

Raising NotImplementedError in a base class only fails when the method is called. An abstract class fails earlier — as soon as someone tries to create an incomplete object.

Why it matters

Abstract classes make interfaces explicit and catch missing methods immediately, which is valuable in larger code bases and plugin systems.

Detailed explanation

Import with from abc import ABC, abstractmethod, then define class Shape(ABC).

Decorate required methods with @abstractmethod. Their body is often just ... or a docstring.

Trying to instantiate a class that still has abstract methods raises TypeError.

A subclass becomes concrete (instantiable) only once it overrides every abstract method.

Abstract classes can also contain normal concrete methods that use the abstract ones — a form of the template-method pattern.

Class.__abstractmethods__ lists the methods that are still missing.

The check happens when an object is created, not when the class is defined. An incomplete subclass can therefore exist and be subclassed further, as long as some descendant finally implements everything before instances are made.

Syntax

Python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
def describe(self): # concrete method
return f"area {self.area():.2f}"
  • Inherit from ABC.
  • Mark required methods with @abstractmethod.
  • Incomplete classes cannot be instantiated.

Code examples

Cannot instantiate the abstract class

Python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
def describe(self):
return f"{type(self).__name__} with area {self.area():.2f}"
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14159 * self.r ** 2
print(Circle(1).describe())
try:
Shape()
except TypeError as e:
print("TypeError:", e)
Output
Circle with area 3.14
TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'

An incomplete subclass

Python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
@abstractmethod
def perimeter(self): ...
class Square(Shape):
def __init__(self, s):
self.s = s
def area(self):
return self.s ** 2
print(sorted(Square.__abstractmethods__))
try:
Square(2)
except TypeError:
print("Square is still abstract")
Output
['perimeter']
Square is still abstract

More examples

Exporters with a shared algorithm

Python
from abc import ABC, abstractmethod
class Exporter(ABC):
def export(self, rows):
lines = [self.header(list(rows[0].keys()))]
lines += [self.line(r) for r in rows]
return "\n".join(lines)
@abstractmethod
def header(self, keys): ...
@abstractmethod
def line(self, row): ...
class CsvExporter(Exporter):
def header(self, keys):
return ",".join(keys)
def line(self, row):
return ",".join(str(v) for v in row.values())
class MarkdownExporter(Exporter):
def header(self, keys):
return "| " + " | ".join(keys) + " |\n|" + "---|" * len(keys)
def line(self, row):
return "| " + " | ".join(str(v) for v in row.values()) + " |"
rows = [{"name": "Asha", "marks": 91}, {"name": "Ravi", "marks": 78}]
print(CsvExporter().export(rows))
print("--")
print(MarkdownExporter().export(rows))
Output
name,marks
Asha,91
Ravi,78
--
| name | marks |
|---|---|
| Asha | 91 |
| Ravi | 78 |

Step-by-step explanation

  • export is concrete and identical for every format.
  • header and line are abstract, so each exporter must provide them.
  • A new format, such as HTML, only needs those two methods.

Expected output

Running “Exporters with a shared algorithm” prints exactly:

TextOutput
name,marks
Asha,91
Ravi,78
--
| name | marks |
|---|---|
| Asha | 91 |
| Ravi | 78 |

Practical applications

  • collections.abc.Mapping and Iterable define the interfaces of Python's containers.
  • Plugin systems require plugins to subclass an abstract Plugin class.

Best practices

  • Use ABCs for interfaces with several implementations.
  • Keep abstract methods few and well documented.
  • Put shared algorithms in concrete methods of the ABC.

Common mistakes

Forgetting to inherit from ABC

Avoid

class Shape:
@abstractmethod
def area(self): ...

Prefer

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

Without ABC (or ABCMeta) the decorator isn't enforced and Shape() succeeds.

Important notes

  • typing.Protocol offers structural interfaces checked by type checkers without inheritance.

Key takeaways

  • Inherit from ABC and use @abstractmethod.
  • Abstract classes can't be instantiated.
  • Subclasses must implement every abstract method.

Try it yourself

  1. 1
    Create an abstract Notifier with send(), and Email and SMS implementations.
  2. 2
    Add an HtmlExporter to the exporter example.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat happens when Shape() is created?
Practise this topic