collections.abc ---容器的抽象基类

3.3 新版功能: 以前,这个模块是 collections 模块。

源代码: Lib/_collections_abc.py


本模块提供 abstract base classes 它可以用来测试一个类是否提供了一个特定的接口;例如,它是可hash的还是映射的。

集合抽象基类

Collections模块提供以下功能 ABCs

ABC

继承自

抽象方法

混合法

Container

__contains__

Hashable

__hash__

Iterable

__iter__

Iterator

Iterable

__next__

__iter__

Reversible

Iterable

__reversed__

Generator

Iterator

send, throw

close, __iter__, __next__

Sized

__len__

Callable

__call__

Collection

Sized, Iterable, Container

__contains__, __iter__, __len__

Sequence

Reversible, Collection

__getitem__, __len__

__contains__, __iter__, __reversed__, index, and count

MutableSequence

Sequence

__getitem__, __setitem__, __delitem__, __len__, insert

继承 Sequence 方法和 appendreverseextendpopremove__iadd__

ByteString

Sequence

__getitem__, __len__

继承 Sequence 方法

Set

Collection

__contains__, __iter__, __len__

__le__, __lt__, __eq__, __ne__, __gt__, __ge__, __and__, __or__, __sub__, __xor__, and isdisjoint

MutableSet

Set

__contains__, __iter__, __len__, add, discard

继承 Set 方法和 clearpopremove__ior____iand____ixor____isub__

Mapping

Collection

__getitem__, __iter__, __len__

__contains__, keys, items, values, get, __eq__, and __ne__

MutableMapping

Mapping

__getitem__, __setitem__, __delitem__, __iter__, __len__

继承 Mapping 方法和 poppopitemclearupdatesetdefault

MappingView

Sized

__len__

ItemsView

MappingView, Set

__contains__, __iter__

KeysView

MappingView, Set

__contains__, __iter__

ValuesView

MappingView, Collection

__contains__, __iter__

Awaitable

__await__

Coroutine

Awaitable

send, throw

close

AsyncIterable

__aiter__

AsyncIterator

AsyncIterable

__anext__

__aiter__

AsyncGenerator

AsyncIterator

asend, athrow

aclose, __aiter__, __anext__

class collections.abc.Container

ABC课程提供 __contains__() 方法。

class collections.abc.Hashable

ABC课程提供 __hash__() 方法。

class collections.abc.Sized

ABC课程提供 __len__() 方法。

class collections.abc.Callable

ABC课程提供 __call__() 方法。

class collections.abc.Iterable

ABC课程提供 __iter__() 方法。

检查 isinstance(obj, Iterable) 检测注册为 Iterable 或者有一个 __iter__() 方法,但它不检测使用 __getitem__() 方法。确定对象是否为 iterable 是调用来的 iter(obj) .

class collections.abc.Collection

大小不可更改容器类的ABC。

3.6 新版功能.

class collections.abc.Iterator

ABC课程提供 __iter__()__next__() 方法。另见定义 iterator .

class collections.abc.Reversible

ABC为也提供 __reversed__() 方法。

3.6 新版功能.

class collections.abc.Generator

ABC用于实现中定义的协议的生成器类 PEP 342 它用 send()throw()close() 方法。另见定义 generator .

3.5 新版功能.

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

只读和可变的ABC sequences .

实现说明:一些混合方法,例如 __iter__()__reversed__()index() ,重复调用基础 __getitem__() 方法。因此,如果 __getitem__() 以恒定的访问速度实现时,mixin方法将具有线性性能;但是,如果底层方法是线性的(与链表一样),则mixin将具有二次性能,并且可能需要重写。

在 3.5 版更改: index()方法增加了对 stop开始 参数。

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

只读和可变集的ABC。

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

只读和可变的ABC mappings .

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

映射、项、键和值的ABC views .

class collections.abc.Awaitable

抽象基类 awaitable 对象,可用于 await 表达。自定义实现必须提供 __await__() 方法。

Coroutine 的对象和实例 Coroutine ABC都是这个ABC的例子。

注解

在CPython中,基于生成器的协程(生成器装饰有 types.coroutine()asyncio.coroutine()等待者 即使他们没有 __await__() 方法。使用 isinstance(gencoro, Awaitable) 因为他们会回来 False . 使用 inspect.isawaitable() 来检测它们。

3.5 新版功能.

class collections.abc.Coroutine

ABC用于协程兼容类。这些方法实现以下方法,在中定义 协程对象send()throw()close() . 自定义实现还必须实现 __await__() . 所有 Coroutine 实例也是 Awaitable . 另见定义 coroutine .

注解

在CPython中,基于生成器的协程(生成器装饰有 types.coroutine()asyncio.coroutine()等待者 即使他们没有 __await__() 方法。使用 isinstance(gencoro, Coroutine) 因为他们会回来 False . 使用 inspect.isawaitable() 来检测它们。

3.5 新版功能.

class collections.abc.AsyncIterable

ABC课程提供 __aiter__ 方法。另见定义 asynchronous iterable .

3.5 新版功能.

class collections.abc.AsyncIterator

ABC课程提供 __aiter____anext__ 方法。另见定义 asynchronous iterator .

3.5 新版功能.

class collections.abc.AsyncGenerator

ABC用于实现中定义的协议的异步生成器类 PEP 525PEP 492 .

3.6 新版功能.

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

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 作为混合:

  1. 由于一些集合操作会创建新的集合,因此默认的混合方法需要一种从可迭代对象创建新实例的方法。假定类构造函数具有以下形式的签名 ClassName(iterable) 。该假设被分解到一个名为 _from_iterable() 哪个呼叫 cls(iterable) 生产一套新的。如果 Set Mixin正在具有不同构造函数签名的类中使用,您需要重写 _from_iterable() 使用可以从可迭代参数构造新实例的类方法或常规方法。

  2. 为了覆盖比较(可能是为了速度,因为语义是固定的),重新定义 __le__()__ge__() ,其他操作将自动跟随。

  3. 这个 Set Mixin提供 _hash() 方法计算集合的hash值;但是, __hash__() 未定义,因为并非所有集都是可hash或不可变的。若要使用mixin添加set hashability,请从两者继承 Set()Hashable() 然后定义 __hash__ = Set._hash .

参见