Introduction
This module provides the infrastructure for defining abstract base classes (ABCs) in Python. The ABCs define a minimal set of methods that establish the characteristic behavior of the type. For more details about this, see PEP 3119.
Highlights
The module provides a metaclass used to create ABCs. An ABC can be subclassed directly. The class also has a 'register' method to register unrelated concrete classes (including built-in classes) and unrelated ABCs as 'virtual subclasses'
Also there are two decorators abstractmethod and abstractproperty, which will set the function object's attribute '__isabstractmethod__' to True. Only when all of the abstract methods and abstract properties are overriden, can a class that has a metaclass derived from ABCMeta be instantiated.
Code comments
ABCMeta.__new__
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
- It first creates a 'type' object cls. (super(ABCMeta, mcls) is 'type')
- Iterate through all the attributes (including all the attributes inherited from all the bases), if any of them have '__isabstractmethod__' set to true, add it to cls's __abstractmethods__.
- Initialize the attributes '_abc_registry', '_abc_cache', '_abc_negative_cache' and '_abc_negative_cache_version', which are used to speed up the check in __instancecheck__ and __subclasscheck__.
ABCMeta.register(cls, subclass)
See the added comments in line
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
ABCMeta.__instancecheck__
See the added comments in line
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
ABCMeta.__subclasscheck__
The code and comment in this function is very clear and straightforward.
Just make sure the different cases needed to check:
- check the subclass hook
- check if it's a direct subclass through __mro__
- check if it's a subclass of a registered class (issubclass is called to do recursive check)
- check if it's a subclass of a subclass (issubclass is called to do recursive check)
In this post, we only talk about the defitions of ABCMeta. We will see the typical usages in the collections module.