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.
- A Python abstract class inherits from
abc.ABCand marks required methods with@abstractmethod. - Instantiating it, or a subclass that skips any abstract method, raised
TypeErrornaming exactly which methods were missing. - Abstract methods can contain real code that subclasses reuse through
super(). register()made an unrelated class passisinstancechecks without inheriting any methods, and aruntime_checkableProtocol 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
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.