How to Use Abstract Base Classes (ABC) in Python

Abstract base classes in Python come from the abc module: subclass abc.ABC and put @abstractmethod on every method a child class must supply. Python then refuses to create objects from any class that still has an abstract method left:

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    @abstractmethod
    def charge(self, amount): ...

PaymentMethod() now raises TypeError, while a subclass that writes charge() works like any normal class.

In this tutorial, I’ll use abstract base classes in Python to model the payment options of an online store checkout, from the first @abstractmethod to virtual subclasses and collections.abc.

Every output and screenshot below came from Python 3.12.5 on Windows 11, run in VS Code.

What is an abstract base class in Python?

An abstract base class (ABC) is a class that defines which methods its children must have, but can’t be instantiated itself. It’s a contract: every payment method at checkout must know how to charge().

Here’s the smallest useful version, with one real subclass:

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    @abstractmethod
    def charge(self, amount): ...

class CreditCard(PaymentMethod):
    def charge(self, amount):
        return f"Charged ${amount:,.2f} to a Visa card"

print(CreditCard().charge(84.50))
try:
    PaymentMethod()
except TypeError as err:
    print("TypeError:", err)

Output:

Charged $84.50 to a Visa card
TypeError: Can't instantiate abstract class PaymentMethod without an implementation for abstract method 'charge'
VS Code running a Python abstract base class example: CreditCard charges $84.50 and PaymentMethod() raises TypeError
The subclass works; creating the abstract class itself stops with TypeError.

CreditCard().charge(84.50) returns Charged $84.50 to a Visa card. Creating PaymentMethod itself fails because its charge() is still abstract.

An abstract class can also hold regular methods, which is the main difference from a plain template; abstract vs concrete classes in Python compares the two side by side.

Why does Python say “Can’t instantiate abstract class”?

You get this TypeError when a class still has at least one abstract method without an implementation. Here, PayPal writes charge() but forgets refund():

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    @abstractmethod
    def charge(self, amount): ...
    @abstractmethod
    def refund(self, amount): ...

class PayPal(PaymentMethod):
    def charge(self, amount):
        return f"PayPal charged ${amount:,.2f}"

try:
    PayPal()
except TypeError as err:
    print("TypeError:", err)

Output:

TypeError: Can't instantiate abstract class PayPal without an implementation for abstract method 'refund'
VS Code output of the Python TypeError naming refund as the abstract method PayPal never implemented
The error names exactly which abstract method is still missing: refund.

If you want the list before anything fails, PayPal.__abstractmethods__ holds the same names. Two details matter. The check runs when you create an object, not when Python reads the class, so a broken subclass can sit in your code until something calls it.

Also, the message changed in Python 3.12. Older versions say with abstract method refund; 3.12 and later say without an implementation for abstract method ‘refund’.

The fix is always to write the missing method in the subclass. I lean on this check in the factory pattern in Python, where every product class has to follow the same interface.

Add concrete methods and reuse an abstract method with super()

ABCs aren’t only lists of rules. A regular method such as checkout() can call the abstract one, and an abstract method may still have a body that subclasses reach through super():

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    fee_rate = 0.029

    def checkout(self, amount):
        fee = round(amount * self.fee_rate + 0.30, 2)
        return f"{self.charge(amount)}, processing fee ${fee:.2f}"

    @abstractmethod
    def charge(self, amount):
        return f"${amount:,.2f}"

class CreditCard(PaymentMethod):
    def charge(self, amount):
        return "Card charged " + super().charge(amount)

print(CreditCard().checkout(84.50))

Output:

Card charged $84.50, processing fee $2.75

checkout() is written once in the base class. The card subclass adds its own wording and reuses the base formatting, giving Card charged $84.50, processing fee $2.75.

super() here works the same way as in constructors; see calling the super constructor in Python for the __init__ side.

How do I make an abstract property in Python?

Stack @property on top of @abstractmethod. The order matters, because @abstractmethod has to be the innermost decorator:

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    @property
    @abstractmethod
    def label(self): ...

class ACHTransfer(PaymentMethod):
    @property
    def label(self):
        return "ACH bank transfer (1-3 business days)"

print(ACHTransfer().label)
print(PaymentMethod.__abstractmethods__)

Output:

ACH bank transfer (1-3 business days)
frozenset({'label'})
VS Code output of a Python abstract property: ACHTransfer prints its label and PaymentMethod lists label as abstract
The subclass’s label property satisfies the abstract one; the base still lists it as abstract.

ACHTransfer().label returns the transfer label, and PaymentMethod.__abstractmethods__ is frozenset({'label'}).

If properties are new to you, my Python property decorator guide covers getters and setters first.

Abstract class methods and static methods

The same stacking works for @classmethod and @staticmethod. The old abstractclassmethod, abstractstaticmethod and abstractproperty helpers have been deprecated since Python 3.3:

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    @classmethod
    @abstractmethod
    def from_token(cls, token): ...

    @staticmethod
    @abstractmethod
    def currency(): ...

class ApplePay(PaymentMethod):
    @classmethod
    def from_token(cls, token):
        return cls()

    @staticmethod
    def currency():
        return "USD"

wallet = ApplePay.from_token("tok_2026_0412")
print(type(wallet).__name__, ApplePay.currency())

try:
    class Broken(ABC):
        @abstractmethod
        @property
        def label(self): ...
except AttributeError as err:
    print("AttributeError:", err)

Output:

ApplePay USD
AttributeError: attribute '__isabstractmethod__' of 'property' objects is not writable

ApplePay builds itself from a token and reports USD. The Broken class shows what happens with the decorators in the wrong order: Python fails while defining the class.

Abstract class methods are a natural fit for alternate constructors; the Python classmethod() function explains cls in detail.

Register a virtual subclass with register()

register() tells an ABC to treat an unrelated class as a subclass, without inheritance. It’s handy for classes you can’t edit, such as a vendor’s SDK. The catch is that Python skips the abstract-method check:

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    @abstractmethod
    def charge(self, amount): ...

@PaymentMethod.register
class GiftCard:
    balance = 25.00

print(issubclass(GiftCard, PaymentMethod))
print(isinstance(GiftCard(), PaymentMethod))
print(PaymentMethod in GiftCard.__mro__)
try:
    GiftCard().charge(25.00)
except AttributeError as err:
    print("AttributeError:", err)

Output:

True
True
False
AttributeError: 'GiftCard' object has no attribute 'charge'
VS Code output of Python ABC register(): GiftCard passes issubclass and isinstance but has no charge method
GiftCard passes both checks, isn’t in the MRO, and fails the moment you call charge().

Both checks print True, yet PaymentMethod isn’t in GiftCard.__mro__, so nothing is inherited and calling charge() raises AttributeError.

Use register() only when you know the class really does the job.

Customize isinstance() checks with __subclasshook__

__subclasshook__ lets an ABC decide membership by looking at a class. This Refundable ABC accepts anything that defines refund():

from abc import ABC, abstractmethod

class Refundable(ABC):
    @abstractmethod
    def refund(self, amount): ...

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Refundable:
            if any("refund" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

class StripeCharge:
    def refund(self, amount):
        return f"Refunded ${amount:,.2f}"

class CashSale:
    pass

print(isinstance(StripeCharge(), Refundable))
print(isinstance(CashSale(), Refundable))

Output:

True
False

StripeCharge never inherits from Refundable, but it passes because it has refund(); CashSale doesn’t. Returning NotImplemented hands the decision back to the normal rules.

The hook runs from ABCMeta, the metaclass behind ABC; Python metaclasses explains how metaclasses hook into class creation.

Use the built-in ABCs in collections.abc

You rarely need to write container ABCs yourself. Subclass collections.abc.Mapping, write three methods, and you get get(), items(), in and more for free:

from collections.abc import Iterable, Mapping, Sized

class PriceList(Mapping):
    def __init__(self, prices):
        self._prices = dict(prices)

    def __getitem__(self, sku):
        return self._prices[sku]

    def __iter__(self):
        return iter(self._prices)

    def __len__(self):
        return len(self._prices)

prices = PriceList({"TX-100": 19.99, "CA-200": 34.50})
print(prices.get("CA-200"), "TX-100" in prices)
print(list(prices.items()))
print(isinstance(prices, Sized), isinstance(prices, Iterable))

class HalfDone(Mapping):
    def __getitem__(self, key): ...

try:
    HalfDone()
except TypeError as err:
    print(err)

Output:

34.5 True
[('TX-100', 19.99), ('CA-200'