abc
— Abstract Base Classes¶
Source code: Lib/abc.py
This module provides the infrastructure for defining abstract base
classes (ABCs) in Python, as outlined in PEP 3119;
see the PEP for why this was added to Python. (See also PEP 3141 and the
numbers
module regarding a type hierarchy for numbers based on ABCs.)
The collections
module has some concrete classes that derive from
ABCs; these can, of course, be further derived. In addition, the
collections.abc
submodule has some ABCs that can be used to test whether
a class or instance provides a particular interface, for example, if it is
hashable or if it is a mapping.
This module provides the metaclass ABCMeta
for defining ABCs and
a helper class ABC
to alternatively define ABCs through inheritance:
- class abc.ABC¶
A helper class that has
ABCMeta
as its metaclass. With this class, an abstract base class can be created by simply deriving fromABC
avoiding sometimes confusing metaclass usage, for example:from abc import ABC class MyABC(ABC): pass
Note that the type of
ABC
is stillABCMeta
, therefore inheriting fromABC
requires the usual precautions regarding metaclass usage, as multiple inheritance may lead to metaclass conflicts. One may also define an abstract base class by passing the metaclass keyword and usingABCMeta
directly, for example:from abc import ABCMeta class MyABC(metaclass=ABCMeta): pass
Added in version 3.4.
- class abc.ABCMeta¶
Metaclass for defining Abstract Base Classes (ABCs).
Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as “virtual subclasses” – these and their descendants will be considered subclasses of the registering ABC by the built-in
issubclass()
function, but the registering ABC won’t show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even viasuper()
). [1]Classes created with a metaclass of
ABCMeta
have the following method:- register(subclass)¶
Register subclass as a “virtual subclass” of this ABC. For example:
from abc import ABC class MyABC(ABC): pass MyABC.register(tuple) assert issubclass(tuple, MyABC) assert isinstance((), MyABC)
Changed in version 3.3: Returns the registered subclass, to allow usage as a class decorator.
Changed in version 3.4: To detect calls to
register()
, you can use theget_cache_token()
function.
You can also override this method in an abstract base class:
- __subclasshook__(subclass)¶
(Must be defined as a class method.)
Check whether subclas