ZetCode

Python abstract classes

last modified November 30, 2026 Python 3.15

In this article we show how to define and use abstract classes in Python.

An abstract class is a base class that is not meant to be instantiated. It declares methods that every subclass must provide, and often also implements shared behaviour on top of them. In Python, abstract classes are written with the abc module: a class derives from ABC, and the required methods are marked with the @abstractmethod decorator. Python then refuses to create objects of any class that still has unimplemented abstract methods.

The article builds on Python methods and Python property decorator.

A base class without abc

Before the abc module, the usual way to require a method was a base implementation that raises NotImplementedError.

not_implemented.py
class Shape:

    def area(self):
        raise NotImplementedError("subclasses must implement area")


class Square(Shape):

    def __init__(self, side):
        self.side = side


sq = Square(3)
print("object created")

try:
    print(sq.area())
except NotImplementedError as e:
    print(e)

The Square subclass forgets to implement area. Python creates the object without complaint, and the mistake is found only when area is called, which may be much later or never in testing.

$ python not_implemented.py
object created
subclasses must implement area

An abstract base class

An abstract base class derives from abc.ABC and marks the required methods with @abstractmethod. The body of an abstract method is often just pass.

abc_basic.py
from abc import ABC, abstractmethod


class Shape(ABC):

    @abstractmethod
    def area(self):
        pass


class Square(Shape):

    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2


sq = Square(3)
print(sq.area())
print(isinstance(sq, Shape))

try:
    Shape()
except TypeError as e:
    print(e)

Shape declares an abstract area method. Square implements it, so it is a concrete class and can be instantiated; a square is also an instance of Shape. Trying to instantiate Shape itself raises a TypeError that names the missing method.

$ python abc_basic.py
9
True
Can't instantiate abstract class Shape without an implementation for abstract method 'area'

Incomplete subclasses

The check is done when an object is created. A subclass that implements only some of the abstract methods is still abstract.

incomplete.py
from abc import ABC, abstractmethod


class Shape(ABC):

    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass


class Square(Shape):

    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2


try:
    Square(3)
except TypeError as e:
    print(e)


class FullSquare(Square):

    def perimeter(self):
        return 4 * self.side


print(FullSquare(3).perimeter())

Square implements area but not perimeter, so creating a square fails immediately with a clear message, instead of failing later on a call as in the first example. FullSquare adds the missing method and inherits area from Square; it is concrete.

$ python incomplete.py
Can't instantiate abstract class Square without an implementation for abstract method 'perimeter'
12

Concrete methods in an abstract class

An abstract class can also contain ordinary methods. They are written in terms of the abstract methods and are inherited by every subclass.

template.py
import math
from abc import ABC, abstractmethod


class Shape(ABC):

    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

    def describe(self):
        name = type(self).__name__
        return (f"{name:9} area {self.area():7.2f}"
                f"  perimeter {self.perimeter():6.2f}")


class Square(Shape):

    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

    def perimeter(self):
        return 4 * self.side


class Circle(Shape):

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

    def perimeter(self):
        return 2 * math.pi * self.radius


for shape in [Square(3), Circle(2), Square(10)]:
    print(shape.describe())

The describe method is implemented once in Shape. It calls area and perimeter, which each subclass implements in its own way, and type(self).__name__ gives the name of the actual class. The loop treats squares and circles alike. This arrangement is known as the template method pattern.

$ python template.py
Square    area    9.00  perimeter  12.00
Circle    area   12.57  perimeter  12.57
Square    area  100.00  perimeter  40.00

Abstract methods with a body

An abstract method can contain a default implementation. Subclasses must still override it, but they can call the base version with super.

default_body.py
from abc import ABC, abstractmethod


class Exporter(ABC):

    @abstractmethod
    def header(self, title):
        return f"Report: {title}"

    def export(self, title, rows):
        lines = [self.header(title)]
        lines.extend(str(row) for row in rows)
        return "\n".join(lines)


class TextExporter(Exporter):

    def header(self, title):
        return super().header(title).upper()


class MarkdownExporter(Exporter):

    def header(self, title):
        return "# " + super().header(title)


rows = [("apples", 4), ("pears", 7)]

print(TextExporter().export("fruit", rows))
print(MarkdownExporter().export("fruit", rows))

The abstract header method builds a basic title. Each exporter overrides it and extends the result of super().header(title): one converts it to uppercase, the other turns it into a Markdown heading. The export method is shared and calls whichever header the subclass provides.

$ python default_body.py
REPORT: FRUIT
('apples', 4)
('pears', 7)
# Report: fruit
('apples', 4)
('pears', 7)

Abstract properties

The @abstractmethod decorator can be combined with @property. It must be the innermost decorator, written directly above def.

abstract_property.py
from abc import ABC, abstractmethod


class Vehicle(ABC):

    @property
    @abstractmethod
    def wheels(self):
        pass

    def describe(self):
        return f"{type(self).__name__} with {self.wheels} wheels"


class Car(Vehicle):

    @property
    def wheels(self):
        return 4


class Bicycle(Vehicle):
    wheels = 2


class Truck(Vehicle):

    def __init__(self, axles):
        self.axles = axles

    @property
    def wheels(self):
        return self.axles * 4


for v in [Car(), Bicycle(), Truck(3)]:
    print(v.describe())

try:
    Car().wheels = 6
except AttributeError as e:
    print(e)

Every vehicle must provide wheels. Car and Truck implement it as a property; the truck computes the value from its axles. Bicycle satisfies the requirement with a plain class attribute, because the check only verifies that the name is no longer abstract. Since Car.wheels is a property without a setter, it cannot be assigned. The same stacking works with @classmethod and @staticmethod.

$ python abstract_property.py
Car with 4 wheels
Bicycle with 2 wheels
Truck with 12 wheels
property 'wheels' of 'Car' object has no setter

Inspecting abstract classes

Python records the names of the unimplemented abstract methods in the __abstractmethods__ attribute of the class. The inspect.isabstract function tells whether a class is still abstract.

inspect_abc.py
import inspect
from abc import ABC, abstractmethod


class Storage(ABC):

    @abstractmethod
    def load(self, key):
        pass

    @abstractmethod
    def save(self, key, value):
        pass

    @classmethod
    @abstractmethod
    def from_url(cls, url):
        pass


class MemoryStorage(Storage):

    def load(self, key):
        return self.data[key]

    def save(self, key, value):
        self.data[key] = value


print(sorted(Storage.__abstractmethods__))
print(sorted(MemoryStorage.__abstractmethods__))
print(inspect.isabstract(Storage), inspect.isabstract(MemoryStorage))
print(type(Storage).__name__)

Storage has three abstract methods, one of them an abstract class method. MemoryStorage implements load and save, but it forgot from_url, so it is still abstract and its __abstractmethods__ lists the remaining name. The type of an abstract base class is ABCMeta; deriving from ABC is a short way of using this metaclass, which performs the checks. Metaclasses are covered in Python metaclasses.

$ python inspect_abc.py
['from_url', 'load', 'save']
['from_url']
True True
ABCMeta

Virtual subclasses

A class can be registered as a virtual subclass of an abstract class with the register method, without inheriting from it.

virtual.py
from abc import ABC, abstractmethod


class Plugin(ABC):

    @abstractmethod
    def run(self):
        pass


class Spellcheck:

    def run(self):
        return "checking spelling"


class Broken:
    pass


Plugin.register(Spellcheck)
Plugin.register(Broken)

for cls in [Spellcheck, Broken]:
    obj = cls()
    print(cls.__name__, isinstance(obj, Plugin), issubclass(cls, Plugin))

print(Plugin in Spellcheck.__mro__)
print(Spellcheck().run())

try:
    Broken().run()
except AttributeError as e:
    print(e)

After registration, isinstance and issubclass report both classes as plugins. Registration is only a declaration: the abstract class does not appear in the method resolution order, nothing is inherited, and the abstract methods are not checked. Broken has no run method, and the error appears only when the method is called. Registration is useful for classes we cannot change, such as classes from another library.

$ python virtual.py
Spellcheck True True
Broken True True
False
checking spelling
'Broken' object has no attribute 'run'

The abstract classes of collections.abc

The collections.abc module defines abstract classes for the container protocols, such as Iterable, Sequence, and Mapping. They are used to test what kind of container an object is.

builtin_abcs.py
from collections.abc import Iterable, Mapping, MutableSequence, Sequence


class Countdown:

    def __init__(self, start):
        self.start = start

    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1


values = [[1, 2], (1, 2), "ab", {"a": 1}, {1, 2}, 42, Countdown(3)]
abcs = [Iterable, Sequence, MutableSequence, Mapping]

print(f"{'':10}" + "".join(f"{a.__name__:>16}" for a in abcs))

for value in values:
    name = type(value).__name__
    row = "".join(f"{str(isinstance(value, a)):>16}" for a in abcs)
    print(f"{name:10}" + row)

print(list(Countdown(3)))

The built-in types are registered with the matching abstract classes: a list is a mutable sequence, a tuple and a string are immutable sequences, and a dictionary is a mapping. Some abstract classes, such as Iterable, also recognize classes by their methods. The Countdown class neither inherits from Iterable nor is registered with it, yet it counts as iterable because it defines __iter__. Checking for Iterable or Mapping is more general than checking for list or dict.

$ python builtin_abcs.py
                  Iterable        Sequence MutableSequence         Mapping
list                  True            True            True           False
tuple                 True            True           False           False
str                   True            True           False           False
dict                  True           False           False            True
set                   True           False           False           False
int                  False           False           False           False
Countdown             True           False           False           False
[3, 2, 1]

Source

abc – Abstract Base Classes, collections.abc, PEP 3119 – Introducing Abstract Base Classes

In this article we have defined abstract base classes with ABC and @abstractmethod, seen how Python rejects incomplete subclasses, combined abstract and concrete methods, called default implementations with super, declared abstract properties, inspected abstract classes, registered virtual subclasses, and tested objects against the abstract classes of collections.abc. See also Python methods, Python metaclasses, and Python magic methods.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.