8.4. collections.abc —— 容器的抽象基类

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

源码位置: Lib/_collections_abc.py

此模块提供抽象基类,可用于测试类是否提供特定接口;例如,它是否是哈希表或者它是否是映射。

8.4.1.容器抽象基类

collections模块提供以下抽象基类

抽象基类继承自抽象的方法Mixin方法
Container__contains__
Hashable__hash__
Iterable__iter__
IteratorIterable__next____iter__
GeneratorIteratorsendthrowclose__iter____next__
Sized__len__
Callable__call__
SequenceSizedIterableContainer__getitem____len____contains____iter____reversed__indexcount
MutableSequenceSequence__getitem__, __setitem__, __delitem__, __len__, insertInherited Sequence methods and append, reverse, extend, pop, remove, and __iadd__
ByteStringSequence__getitem____len__继承Sequence方法
SetSizedIterableContainer__contains____iter____len____le__, __lt__, __eq__, __ne__, __gt__, __ge__, __and__, __or__, __sub__, __xor__, and isdisjoint
MutableSetSet__contains____iter____len__adddiscardInherited Set methods and clear, pop, remove, __ior__, __iand__, __ixor__, and __isub__
MappingSizedIterableContainer__getitem____iter____len____contains__, keys, items, values, get, __eq__, and __ne__
MutableMappingMapping__getitem____setitem____delitem____iter____len__继承Mapping方法和poppopitemclearupdatesetdefault
MappingViewSized__len__
ItemsViewMappingViewSet__contains____iter__
KeysViewMappingViewSet__contains____iter__
ValuesViewMappingView__contains____iter__
Awaitable__await__
CoroutineAwaitablesendthrowclose
AsyncIterable__aiter__
AsyncIteratorAsyncIterable__anext____aiter__
class collections.abc.Container
class collections.abc.Hashable
class collections.abc.Sized
class collections.abc.Callable

分别为类提供__contains__()__hash__()__len__()__call__()方法的抽象基类。

class collections.abc.Iterable

提供__iter__()方法的类的ABC。另请参见iterable的定义。

class collections.abc.Iterator

提供__iter__()__next__()方法的类的ABC。另请参见iterator的定义。

class collections.abc.Generator

ABC for generator classes that implement the protocol defined in PEP 342 that extends iterators with the send(), throw() and close() methods. 另见generator的定义。

版本3.5中的新功能。

class collections.abc.Sequence
class collections.abc.MutableSequence
class collections.abc.ByteString

只读和可变sequences的ABCs。

实现注意:一些mixin方法,如__iter__()__reversed__()index() __getitem__()方法。因此,如果__getitem__()以常量访问速度实现,则mixin方法将具有线性性能;然而,如果底层方法是线性的(因为它将与一个链表),mixins将具有二次性能,可能需要重写。

在版本3.5中更改: index()方法添加了对停止开始参数的支持。

class collections.abc.Set
class collections.abc.MutableSet

ABCs用于只读和可变集。

class collections.abc.Mapping
class collections.abc.MutableMapping

只读和可变mappings的ABCs。

class collections.abc.MappingView
class collections.abc.ItemsView
class collections.abc.KeysView
class collections.abc.ValuesView

用于映射的ABCs,项目,键和值views

class collections.abc.Awaitable

用于awaitable对象的ABC,可用于await表达式中。自定义实现必须提供__ await __()方法。

协程对象和协程 ABC的实例都是此ABC的实例。

注意

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

版本3.5中的新功能。

class collections.abc.Coroutine

协程兼容类ABC。这些实现在协程对象中定义的以下方法:send()throw(),和close() 自定义实现还必须实现__ await __()所有协程实例也是Awaitable的实例。另见协程的定义。

注意

在CPython中,基于生成器的协程(types.coroutine()asyncio.coroutine()装饰的生成器是awaitables虽然他们没有__await__()方法。使用isinstance(gencoro, 协程),将返回False使用inspect.isawaitable()检测它们。

版本3.5中的新功能。

class collections.abc.AsyncIterable

ABC提供__aiter__方法的类。另请参见asynchronous iterable的定义。

版本3.5中的新功能。

class collections.abc.AsyncIterator

提供__aiter____anext__方法的类的ABC。另请参见asynchronous iterator的定义。

版本3.5中的新功能。

这些ABC允许我们询问类或实例,如果它们提供特定的功能,例如:

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

几个ABCs也可用作mixin,使得更容易开发支持容器API的类。For example, to write a class supporting the full Set API, it is only necessary to supply the three underlying abstract methods: __contains__(), __iter__(), and __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作为混合的注意事项:

  1. 因为一些集合操作创建新集合,所以默认的mixin方法需要一种从迭代中创建新实例的方法。类构造函数假定具有ClassName(iterable)形式的声明。该假设被分解为调用cls(iterable)的一个名为_from_iterable()的内部类方法,以产生一个新集合。如果在具有不同构造函数声明的类中使用Set mixin,则需要使用可以从可迭代参数构造新实例的类方法覆盖_from_iterable()
  2. 要覆盖比较(假定为速度,因为语义是固定的),重新定义__le__()__ge__(),则其他操作将自动跟随。
  3. Set mixin提供了一个_hash()方法来计算集合的哈希值;然而,__hash__()未定义,因为并非所有集都是可哈希的或不可变的。要使用mixins添加集合散列,请继承Set()Hashable(),然后定义__ hash __ = Set._hash

也可以看看