collections.abc --- 容器的抽象基底類別¶
在 3.3 版被加入: 過去此模組是 collections 模組的一部分。
This module provides abstract base classes that can be used to test whether a class provides a particular interface; for example, whether it is hashable or whether it is a mapping.
An issubclass() or isinstance() test for an interface works in one
of three ways.
A newly written class can inherit directly from one of the abstract base classes. The class must supply the required abstract methods. The remaining mixin methods come from inheritance and can be overridden if desired. Other methods may be added as needed:
class C(Sequence): # Direct inheritance def __init__(self): ... # Extra method not required by the ABC def __getitem__(self, index): ... # Required abstract method def __len__(self): ... # Required abstract method def count(self, value): ... # Optionally override a mixin method
>>> issubclass(C, Sequence) True >>> isinstance(C(), Sequence) True
Existing classes and built-in classes can be registered as "virtual subclasses" of the ABCs. Those classes should define the full API including all of the abstract methods and all of the mixin methods. This lets users rely on
issubclass()orisinstance()tests to determine whether the full interface is supported. The exception to this rule is for methods that are automatically inferred from the rest of the API:class D: # No inheritance def __init__(self): ... # Extra method not required by the ABC def __getitem__(self, index): ... # Abstract method def __len__(self): ... # Abstract method def count(self, value): ... # Mixin method def index(self, value): ... # Mixin method Sequence.register(D) # Register instead of inherit
>>> issubclass(D, Sequence) True >>> isinstance(D(), Sequence) True
In this example, class
Ddoes not need to define__contains__,__iter__, and__reversed__because the in-operator, the iteration logic, and thereversed()function automatically fall back to using__getitem__and__len__.Some simple interfaces are directly recognizable by the presence of the required methods (unless those methods have been set to
None):class E: def __iter__(self): ... def __next__(self): ...
>>> issubclass(E, Iterable) True >>> isinstance(E(), Iterable) True
Complex interfaces do not support this last technique because an interface is more than just the presence of method names. Interfaces specify semantics and relationships between methods that cannot be inferred solely from the presence of specific method names. For example, knowing that a class supplies
__getitem__,__len__, and__iter__is insufficient for distinguishing aSequencefrom aMapping.
Collections Abstract Base Classes¶
The collections module offers the following ABCs:
ABC |
Inherits from |
抽象方法 |
Mixin Methods |
|---|---|---|---|
|
|||
|
|||
|
|||
|
|
||
|
|||
|
|
||
|
|||
|
|||
|
|||
|
|
||
|
繼承 |
||
|
|
||
|
|
||