1. Home
  2. Blog
  3. Software Development

Software Development

Python Abstract Class: ABC, abstractmethod and When to Use Them

A Python abstract class defines methods that every subclass must implement, and refuses to be instantiated until they are. Learn ABC and abstractmethod with a payment gateway example, abstract properties and class methods, shared logic through super(), virtual subclasses, collections.abc, and when a typing Protocol is the better choice, all tested on Python 3.13.

9 min read
Python abstract class: ABC, abstractmethod and when to use them

Key takeaways

  • A Python abstract class inherits from abc.ABC and marks required methods with @abstractmethod.
  • Instantiating it, or a subclass that skips any abstract method, raised TypeError naming exactly which methods were missing.
  • Abstract methods can contain real code that subclasses reuse through super().
  • register() made an unrelated class pass isinstance checks without inheriting any methods, and a runtime_checkable Protocol did the same by structure alone.

When several classes must offer the same operations, such as payment gateways that all charge and refund, storage backends that all read and write, or exporters that all produce a file, you want a guarantee that none of them forgets a method. A Python abstract class gives you that guarantee at the moment an object is created, not hours later when a missing method is finally called in production.

Every example below ran on Python 3.13.6, and the error messages are copied from the run.

Why abstract classes?

An abstract class describes an interface: a list of methods every implementation must provide, plus any shared behaviour. You never create the abstract class itself, only its concrete subclasses. Code that uses the objects can then rely on the interface, which makes it easy to swap a real implementation for a fake one in tests, as described in our test doubles guide.

ABC and abstractmethod

from abc import ABC, abstractmethod

class PaymentGateway(ABC):
    @abstractmethod
    def charge(self, amount: int) -> str: pass

    @abstractmethod
    def refund(self, tx_id: str) -> bool: pass

    def pay_twice(self, amount):            # a normal, shared method
        return [self.charge(amount), self.charge(amount)]

PaymentGateway()
# TypeError: Can't instantiate abstract class PaymentGateway without an
#   implementation for abstract methods 'charge', 'refund'

Inheriting from ABC gives the class the ABCMeta metaclass, which tracks abstract methods. Each method decorated with @abstractmethod must be overridden before the class can be instantiated. The body is usually just pass, an ellipsis or a docstring, and type hints on the signature document what implementations should accept and return.

Partial implementations are caught

class Half(PaymentGateway):
    def charge(self, amount): return f"tx-{amount}"

Half()
# TypeError: Can't instantiate abstract class Half without an
#   implementation for abstract method 'refund'

The error names the exact missing method, and it happens when the object is created. Without the ABC, Half() would succeed and the bug would surface only when someone tried a refund. Subclasses can stay abstract on purpose, adding some methods and leaving others for further subclasses.

A complete subclass

class Fake(PaymentGateway):
    def charge(self, amount): return f"fake-{amount}"
    def refund(self, tx_id): return True

f = Fake()
f.pay_twice(5)                    # ['fake-5', 'fake-5']
isinstance(f, PaymentGateway)     # True

Once every abstract method is implemented, the class works like any other, inherits the shared pay_twice method and passes isinstance checks against the base. Concrete gateways for real providers would follow the same pattern, and the rest of the application only ever depends on PaymentGateway.

Inspecting abstract methods

sorted(PaymentGateway.__abstractmethods__)   # ['charge', 'refund']
Fake.__abstractmethods__                     # frozenset()
inspect.isabstract(PaymentGateway)           # True
inspect.isabstract(Fake)                     # False

Every ABC records the names of its unimplemented methods in __abstractmethods__. Plugin loaders and test suites can use inspect.isabstract to skip base classes when discovering implementations automatically.

Abstract properties, class methods and static methods

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

    @classmethod
    @abstractmethod
    def unit(cls): pass

    @staticmethod
    @abstractmethod
    def kind(): pass

class Sq(Shape):
    def __init__(self, s): self.s = s
    @property
    def area(self): return self.s ** 2
    @classmethod
    def unit(cls): return "cm"
    @staticmethod
    def kind(): return "square"

Sq(3).area, Sq.unit(), Sq.kind()     # (9, 'cm', 'square')

Stack @abstractmethod innermost, directly above the function, with @property, @classmethod or @staticmethod above it. The older abstractproperty and abstractclassmethod helpers are deprecated in favour of this stacking. Properties themselves are covered in our Python property guide.

Abstract methods with shared logic

class Base(ABC):
    @abstractmethod
    def save(self):
        return "base logic"

class Impl(Base):
    def save(self):
        return super().save() + " + impl"

Impl().save()     # 'base logic + impl'

Unlike in Java, a Python abstract method may have a body. Subclasses still must override it, but they can call the base version through super() to reuse common steps such as validation or logging. This “template” style keeps shared behaviour in one place while forcing each subclass to decide how to finish the job.

Virtual subclasses with register()

class Duck:
    def charge(self, a): return "duck"
    def refund(self, t): return False

PaymentGateway.register(Duck)
isinstance(Duck(), PaymentGateway)     # True
issubclass(Duck, PaymentGateway)       # True
hasattr(Duck, "pay_twice")             # False

register() declares that an existing class, perhaps from a third-party library you cannot edit, counts as an implementation. Be careful: it is a promise, not a check. Python did not verify that Duck implements anything, and Duck did not inherit the shared pay_twice method. Code that calls it would fail with AttributeError.

Structural checks with __subclasshook__

class Sized(ABC):
    @classmethod
    def __subclasshook__(cls, C):
        return any("__len__" in B.__dict__ for B in C.__mro__) or NotImplemented

isinstance([1], Sized)    # True
isinstance(3, Sized)      # False

__subclasshook__ lets an ABC decide membership by inspecting a class, here “has a __len__ method anywhere in its hierarchy”. A list passed without inheriting or registering, an integer did not. This is how the built-in abstract classes recognise ordinary types.

Built-in abstract classes: collections.abc

from collections.abc import Iterable, Mapping, MutableMapping
isinstance({}, Mapping)     # True
isinstance("ab", Iterable)  # True
isinstance(5, Iterable)     # False

class BadDict(MutableMapping): pass
BadDict()
# TypeError: Can't instantiate abstract class BadDict without an implementation for
#   abstract methods '__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__'

The standard library ships abstract classes for every container protocol. Checking isinstance(x, Mapping) is more flexible than isinstance(x, dict), because it accepts any mapping type. Inheriting from MutableMapping and implementing the five listed methods gives you get, items, update, pop and the rest for free, which is the easiest way to build a custom dictionary-like class; see our Python dictionary guide for the methods you inherit.

Adding abstract methods later

class Late(ABC): pass
Late.m = abstractmethod(lambda self: None)
Late()                                # still works

from abc import update_abstractmethods
update_abstractmethods(Late)
Late()
# TypeError: Can't instantiate abstract class Late without an implementation for abstract method 'm'

The set of abstract methods is calculated when the class is created. Adding one afterwards, for example from a class decorator, has no effect until you call abc.update_abstractmethods, available since Python 3.10. Our test showed both halves: the class stayed instantiable, then refused after the update.

ABC vs typing.Protocol

from typing import Protocol, runtime_checkable

@runtime_checkable
class Charger(Protocol):
    def charge(self, amount: int) -> str: pass

isinstance(Duck(), Charger)      # True   (has a charge method, no inheritance)
isinstance(object(), Charger)    # False
Aspect ABC Protocol
Membership Inherit or register Any class with matching methods
Enforced when At instantiation By the type checker; runtime only checks method names
Shared code Yes, inherited No (not meant for inheritance)
Best for Your own class hierarchies and plugin bases Accepting third-party objects by shape

Protocols describe “anything that looks like this” for static type checkers such as mypy, which fits Python’s duck typing. ABCs enforce a contract at runtime and can share code. Many codebases use both: an ABC for the classes they own, and a Protocol in function signatures that should accept any compatible object.

When to use an abstract class

  • Use one when you have several interchangeable implementations of the same role: gateways, storage backends, notifiers, exporters, test fakes.
  • Use one for plugin systems, where third parties add implementations you never see.
  • Skip it for a single implementation; a plain class is simpler, and you can extract an ABC later.
  • Skip it for pure data; dataclasses are a better fit, and they work with ABCs if you need both.
  • Prefer a Protocol when you only need to describe what a function accepts.

For the basics of inheritance and method overriding, start with our Python classes and objects guide.

Final thoughts

A Python abstract class turns an informal “every subclass should have these methods” into a rule Python enforces the moment an object is created. Inherit from ABC, mark required methods with @abstractmethod (innermost when combined with property or classmethod), put shared logic in normal or abstract methods, and remember that register() and Protocols check far less than real inheritance. Our tests showed the payoff: missing methods were named precisely, at construction time, before any of them could fail in use.

Frequently asked questions

How do I create an abstract class in Python?

Import ABC and abstractmethod from the abc module, inherit your class from ABC and decorate each required method with abstractmethod. Subclasses must implement those methods before they can be instantiated.

Can an abstract class have a constructor?

Yes. An abstract class can define an init method with shared setup. Subclasses inherit it or call it with super, but the abstract class itself still cannot be instantiated directly.

Can abstract methods have code in Python?

Yes. Unlike Java, a Python abstract method may contain a body. Subclasses must still override it, but they can call the base version through super to reuse that logic.

What is the difference between an abstract class and an interface in Python?

Python has no separate interface keyword. An abstract class with only abstract methods acts as an interface, while typing Protocol describes an interface by structure for type checkers.

How do I make an abstract property?

Stack the property decorator above abstractmethod on the same function. Subclasses then must provide a property, or any attribute, with that name.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →