collections.abc --- 容器的抽象基底類別

在 3.3 版被加入: 過去此模組是 collections 模組的一部分。

原始碼:Lib/_collections_abc.py


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.

  1. 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
    
  2. 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() or isinstance() 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 D does not need to define __contains__, __iter__, and __reversed__ because the in-operator, the iteration logic, and the reversed() function automatically fall back to using __getitem__ and __len__.

  3. 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 a Sequence from a Mapping.

在 3.9 版被加入: These abstract classes now support []. See 泛型別名型別 and PEP 585.

Collections Abstract Base Classes

The collections module offers the following ABCs:

ABC

Inherits from

抽象方法

Mixin Methods

Container [1]

__contains__

Hashable [1]

__hash__

Iterable [1] [2]

__iter__

Iterator [1]

Iterable

__next__

__iter__

Reversible [1]

Iterable

__reversed__

Generator [1]

Iterator

sendthrow

close__iter____next__

Sized [1]

__len__

Callable [1]

__call__

Collection [1]

SizedIterableContainer

__contains____iter____len__

Sequence

Reversible, Collection

__getitem____len__

__contains____iter____reversed__indexcount

MutableSequence

Sequence

__getitem____setitem____delitem____len__insert

繼承 Sequence 方法和 appendclearreverseextendpopremove__iadd__

ByteString

Sequence

__getitem____len__

Sequence 的繼承方法

Set

Collection

__contains____iter____len__

__le____lt____eq____ne____gt____ge____and____or____sub____rsub____xor____rxor__isdisjoint

MutableSet