Python Reference ยท Classes and Special Methods
Abstract base classes
Concept guide to Python abstract base classes: the abc module, @abstractmethod, enforcing interfaces, virtual subclasses and collections.abc.
An abstract base class (ABC) describes an interface that subclasses must implement. You cannot create an instance of an ABC while it still has abstract methods, so a forgotten method shows up as an error at construction time rather than as a surprise deep in the program.
You create one by inheriting from abc.ABC (or using metaclass=ABCMeta) and marking methods with @abstractmethod. ABCs also power isinstance() checks for protocols like "is iterable" through the collections.abc module.
Enforcing an interface
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Abstract methods may have a body, and subclasses can call it with super(). Abstract properties work by stacking @property over @abstractmethod (property first, the abstract decorator innermost).
Virtual subclasses and collections.abc
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
register() declares a class a "virtual subclass" without inheriting from it. Sized and a few other ABCs recognize any class that has the right methods (structural checking via __subclasshook__), so Countdown counts as Sized without any registration.
Key rules
- Abstract means "must override". Instantiation fails with
TypeError: Can't instantiate abstract class ... without an implementation for abstract method .... @abstractmethodonly works when the class has theABCMetametaclass, whichABCprovides.- Decorator order:
@classmethodand@propertygo outside,@abstractmethodis the innermost. - Shared code is fine. Concrete methods in an ABC (like
describe) use the abstract ones; this is the template-method pattern. - Mixin methods from
collections.abc: inherit fromMapping,Sequence,MutableSetand others, implement a few required methods, and get dozens of others free. - Protocols are the alternative.
typing.Protocolchecks interfaces structurally for type checkers without any inheritance. - Do not overuse them. Python usually relies on duck typing; add an ABC when many classes must share a contract, or for plugin systems.
- Registered classes do not inherit behavior and are not checked for abstract methods.