collections.abc —容器的抽象 Base Class

版本 3.3 中的新增Function:以前,此模块是collections模块的一部分。

源代码: Lib/_collections_abc.py


此模块提供抽象 Base Class,可用于测试类是否提供了特定的接口;例如,它是否可散列还是 Map。

集合抽象 Base Class

收款模块提供以下ABCs

ABCInherits fromAbstract MethodsMixin Methods
Container__contains__
Hashable__hash__
Iterable__iter__
IteratorIterable__next____iter__
ReversibleIterable__reversed__
GeneratorIteratorsend , throwclose , __iter__ , __next__
Sized__len__
Callable__call__
CollectionSized, Iterable, Container__contains__ , __iter__ , __len__
SequenceReversible, Collection__getitem__ , __len____contains____iter____reversed__indexcount
MutableSequenceSequence__getitem__ , __setitem__ , __delitem__ , __len__ , insert继承了Sequence个方法以及appendreverseextendpopremove__iadd__
ByteStringSequence__getitem__ , __len__继承的Sequence个方法
SetCollection__contains__ , __iter__ , __len____le____lt____eq____ne____gt____ge____and____or____sub____xor__isdisjoint
MutableSetSet__contains__ , __iter__ , __len__ , add , discard继承了Set个方法以及clearpopremove__ior____iand____ixor____isub__
MappingCollection__getitem__ , __iter__ , __len____contains__keysitemsvaluesget__eq____ne__
MutableMappingMapping__getitem__ , __setitem__ , __delitem__ , __iter__ , __len__继承了Mapping个方法以及poppopitemclearupdatesetdefault
MappingViewSized__len__
ItemsViewMappingView, Set__contains__ , __iter__
KeysViewMappingView, Set__contains__ , __iter__
ValuesViewMappingView, Collection__contains__ , __iter__
Awaitable__await__
CoroutineAwaitablesend , throwclose
AsyncIterable__aiter__
AsyncIteratorAsyncIterable__anext____aiter__
AsyncGeneratorAsyncIteratorasend , athrowaclose , __aiter__ , __anext__
  • 类别 collections.abc. Container

  • 类别 collections.abc. Hashable

  • 类别 collections.abc. Sized

  • 类别 collections.abc. Callable

  • 类别 collections.abc. Iterable

    • 提供iter()方法的类的 ABC。

检查isinstance(obj, Iterable)会检测已注册为Iterable或具有iter()方法的类,但不会检测到使用getitem()方法进行迭代的类。确定对象是否为iterable的唯一可靠方法是调用iter(obj)

  • 类别 collections.abc. Collection
    • 适用于大小可迭代的容器类的 ABC。

3.6 版的新Function。

  • 类别 collections.abc. Iterator

  • 类别 collections.abc. Reversible

    • 还提供reversed()方法的可迭代类的 ABC。

3.6 版的新Function。

  • 类别 collections.abc. Generator

3.5 版中的新Function。

  • 类别 collections.abc. Sequence
  • 类别 collections.abc. MutableSequence
  • 类别 collections.abc. ByteString

实施注意事项:某些 mixin 方法(例如iter()reversed()index())反复调用基础getitem()方法。因此,如果以恒定的访问速度实现getitem(),则 mixin 方法将具有线性性能;但是,如果基础方法是线性的(如链表那样),则混合将具有二次性能,并且可能需要重写。

在版本 3.5 中进行了更改:index()方法添加了对* stop start *参数的支持。

  • 类别 collections.abc. Set

  • 类别 collections.abc. MutableSet

    • 只读和可变集的 ABC。
  • 类别 collections.abc. Mapping

  • 类别 collections.abc. MutableMapping

  • 类别 collections.abc. MappingView

  • 类别 collections.abc. ItemsView

  • 类别 collections.abc. KeysView

  • 类别 collections.abc. ValuesView

    • Map,项目,键和值views的 ABC。
  • 类别 collections.abc. Awaitable

    • awaitable个对象的 ABC,可在await个表达式中使用。定制实现必须提供await()方法。

Coroutine对象和Coroutine ABC 的实例都是此 ABC 的所有实例。

Note

在 CPython 中,即使没有await()方法,基于生成器的协程(以types.coroutine()asyncio.coroutine()装饰的生成器)也是* waitables *。对他们使用isinstance(gencoro, Awaitable)将返回False。使用inspect.isawaitable()来检测它们。

3.5 版中的新Function。

Note

在 CPython 中,即使没有await()方法,基于生成器的协程(以types.coroutine()asyncio.coroutine()装饰的生成器)也是* waitables *。对他们使用isinstance(gencoro, Coroutine)将返回False。使用inspect.isawaitable()来检测它们。

3.5 版中的新Function。

  • 类别 collections.abc. AsyncIterable

3.5 版中的新Function。

  • 类别 collections.abc. AsyncIterator

3.5 版中的新Function。

  • 类别 collections.abc. AsyncGenerator
    • 异步 Generator 类的 ABC,实现了 PEP 525 PEP 492中定义的协议。

3.6 版的新Function。

这些 ABC 允许我们询问类或实例是否提供特定Function,例如:

size = None
if isinstance(myvar, collections.abc.Sized):
    size = len(myvar)

几种 ABC 可用作混合器,使开发支持容器 API 的类更加容易。例如,要编写一个支持完整的Set API 的类,只需提供三个底层抽象方法:contains()iter()len()。 ABC 提供其余方法,例如and()isdisjoint()

class ListBasedSet(collections.abc.Set):
    ''' Alternate set implementation favoring space over speed
        and not requiring the set elements to be hashable. '''
    def __init__(self, iterable):
        self.elements = lst = []
        for value in iterable:
            if value not in lst:
                lst.append(value)

    def __iter__(self):
        return iter(self.elements)

    def __contains__(self, value):
        return value in self.elements

    def __len__(self):
        return len(self.elements)

s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2            # The __and__() method is supported automatically

有关将SetMutableSet用作混合的注意事项:

  • 由于某些集合操作会创建新集合,因此默认的 mixin 方法需要一种从迭代器创建新实例的方法。假定类构造函数具有ClassName(iterable)形式的签名。该假设被分解为称为_from_iterable()的内部类方法,该方法调用cls(iterable)以产生新的集合。如果在具有不同构造函数签名的类中使用Set mixin,则需要使用可以从可迭代参数构造新实例的类方法覆盖_from_iterable()

  • 要覆盖比较(可能是为了提高速度,因为语义是固定的),请重新定义le()ge(),然后其他操作将自动跟随。

  • Set mixin 提供_hash()方法来计算集合的哈希值;但是,未定义hash(),因为并非所有集合都是可哈希的或不可变的。要使用 mixins 添加集散列性,请同时继承Set()Hashable(),然后定义__hash__ = Set._hash

See also