企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](heapq.xhtml "heapq --- 堆队列算法") | - [上一页](collections.xhtml "collections --- 容器数据类型") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [Python 标准库](index.xhtml) » - [数据类型](datatypes.xhtml) » - $('.inline-search').show(0); | # [`collections.abc`](#module-collections.abc "collections.abc: Abstract base classes for containers") --- 容器的抽象基类 3\.3 新版功能: 该模块曾是 [`collections`](collections.xhtml#module-collections "collections: Container datatypes") 模块的组成部分。 **源代码:** [Lib/\_collections\_abc.py](https://github.com/python/cpython/tree/3.7/Lib/_collections_abc.py) \[https://github.com/python/cpython/tree/3.7/Lib/\_collections\_abc.py\] - - - - - - 该模块定义了一些 [抽象基类](../glossary.xhtml#term-abstract-base-class),它们可用于判断一个具体类是否具有某一特定的接口;例如,这个类是否可哈希,或其是否为映射类。 ## Collections Abstract Base Classes The collections module offers the following [ABCs](../glossary.xhtml#term-abstract-base-class): ABC Inherits from Abstract Methods Mixin Methods [`Container`](#collections.abc.Container "collections.abc.Container") `__contains__` [`Hashable`](#collections.abc.Hashable "collections.abc.Hashable") `__hash__` [`Iterable`](#collections.abc.Iterable "collections.abc.Iterable") `__iter__` [`Iterator`](#collections.abc.Iterator "collections.abc.Iterator") [`Iterable`](#collections.abc.Iterable "collections.abc.Iterable") `__next__` `__iter__` [`Reversible`](#collections.abc.Reversible "collections.abc.Reversible") [`Iterable`](#collections.abc.Iterable "collections.abc.Iterable") `__reversed__` [`Generator`](#collections.abc.Generator "collections.abc.Generator") [`Iterator`](#collections.abc.Iterator "collections.abc.Iterator") `send`, `throw` `close`, `__iter__`, `__next__` [`Sized`](#collections.abc.Sized "collections.abc.Sized") `__len__` [`Callable`](#collections.abc.Callable "collections.abc.Callable") `__call__` [`Collection`](#collections.abc.Collection "collections.abc.Collection") [`Sized`](#collections.abc.Sized "collections.abc.Sized"), [`Iterable`](#collections.abc.Iterable "collections.abc.Iterable"), [`Container`](#collections.abc.Container "collections.abc.Container") `__contains__`, `__iter__`, `__len__` [`Sequence`](#collections.abc.Sequence "collections.abc.Sequence") [`Reversible`](#collections.abc.Reversible "collections.abc.Reversible"), [`Collection`](#collections.abc.Collection "collections.abc.Collection") `__getitem__`, `__len__` `__contains__`, `__iter__`, `__reversed__`, `index`, and `count` [`MutableSequence`](#collections.abc.MutableSequence "collections.abc.MutableSequence") [`Sequence`](#collections.abc.Sequence "collections.abc.Sequence") `__getitem__`, `__setitem__`, `__delitem__`, `__len__`, `insert` Inherited [`Sequence`](#collections.abc.Sequence "collections.abc.Sequence") methods and `append`, `reverse`, `extend`, `pop`, `remove`, and `__iadd__` [`ByteString`](#collections.abc.ByteString "collections.abc.ByteString") [`Sequence`](#collections.abc.Sequence "collections.abc.Sequence") `__getitem__`, `__len__` Inherited [`Sequence`](#collections.abc.Sequence "collections.abc.Sequence") methods [`Set`](#collections.abc.Set "collections.abc.Set") [`Collection`](#collections.abc.Collection "collections.abc.Collection") `__contains__`, `__iter__`, `__len__` `__le__`, `__lt__`, `__eq__`, `__ne__`, `__gt__`, `__ge__`, `__and__`, `__or__`, `__sub__`, `__xor__`, and `isdisjoint` [`MutableSet`](#collections.abc.MutableSet "collections.abc.MutableSet") [`Set`](#collections.abc.Set "collections.abc.Set") `__contains__`, `__iter__`, `__len__`, `add`, `discard` Inherited [`Set`](#collections.abc.Set "collections.abc.Set") methods and `clear`, `pop`, `remove`, `__ior__`, `__iand__`, `__ixor__`, and `__isub__` [`Mapping`](#collections.abc.Mapping "collections.abc.Mapping") [`Collection`](#collections.abc.Collection "collections.abc.Collection") `__getitem__`, `__iter__`, `__len__` `__contains__`, `keys`, `items`, `values`, `get`, `__eq__`, and `__ne__` [`MutableMapping`](#collections.abc.MutableMapping "collections.abc.MutableMapping") [`Mapping`](#collections.abc.Mapping "collections.abc.Mapping") `__getitem__`, `__setitem__`, `__delitem__`, `__iter__`, `__len__` Inherited [`Mapping`](#collections.abc.Mapping "collections.abc.Mapping") methods and `pop`, `popitem`, `clear`, `update`, and `setdefault` [`MappingView`](#collections.abc.MappingView "collections.abc.MappingView") [`Sized`](#collections.abc.Sized "collections.abc.Sized") `__len__` [`ItemsView`](#collections.abc.ItemsView "collections.abc.ItemsView") [`MappingView`](#collections.abc.MappingView "collections.abc.MappingView"), [`Set`](#collections.abc.Set "collections.abc.Set") `__contains__`, `__iter__` [`KeysView`](#collections.abc.KeysView "collections.abc.KeysView") [`MappingView`](#collections.abc.MappingView "collections.abc.MappingView"), [`Set`](#collections.abc.Set "collections.abc.Set") `__contains__`, `__iter__` [`ValuesView`](#collections.abc.ValuesView "collections.abc.ValuesView") [`MappingView`](#collections.abc.MappingView "collections.abc.MappingView"), [`Collection`](#collections.abc.Collection "collections.abc.Collection") `__contains__`, `__iter__` [`Awaitable`](#collections.abc.Awaitable "collections.abc.Awaitable") `__await__` [`Coroutine`](#collections.abc.Coroutine "collections.abc.Coroutine") [`Awaitable`](#collections.abc.Awaitable "collections.abc.Awaitable") `send`, `throw` `close` [`AsyncIterable`](#collections.abc.AsyncIterable "collections.abc.AsyncIterable") `__aiter__` [`AsyncIterator`](#collections.abc.AsyncIterator "collections.abc.AsyncIterator") [`AsyncIterable`](#collections.abc.AsyncIterable "collections.abc.AsyncIterable") `__anext__` `__aiter__` [`AsyncGenerator`](#collections.abc.AsyncGenerator "collections.abc.AsyncGenerator") [`AsyncIterator`](#collections.abc.AsyncIterator "collections.abc.AsyncIterator") `asend`, `athrow` `aclose`, `__aiter__`, `__anext__` *class* `collections.abc.``Container`*class* `collections.abc.``Hashable`*class* `collections.abc.``Sized`*class* `collections.abc.``Callable`ABCs for classes that provide respectively the methods [`__contains__()`](../reference/datamodel.xhtml#object.__contains__ "object.__contains__"), [`__hash__()`](../reference/datamodel.xhtml#object.__hash__ "object.__hash__"), [`__len__()`](../reference/datamodel.xhtml#object.__len__ "object.__len__"), and [`__call__()`](../reference/datamodel.xhtml#object.__call__ "object.__call__"). *class* `collections.abc.``Iterable`ABC for classes that provide the [`__iter__()`](../reference/datamodel.xhtml#object.__iter__ "object.__iter__") method. Checking `isinstance(obj, Iterable)` detects classes that are registered as [`Iterable`](#collections.abc.Iterable "collections.abc.Iterable") or that have an [`__iter__()`](../reference/datamodel.xhtml#object.__iter__ "object.__iter__") method, but it does not detect classes that iterate with the [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__") method. The only reliable way to determine whether an object is [iterable](../glossary.xhtml#term-iterable)is to call `iter(obj)`. *class* `collections.abc.``Collection`ABC for sized iterable container classes. 3\.6 新版功能. *class* `collections.abc.``Iterator`ABC for classes that provide the [`__iter__()`](stdtypes.xhtml#iterator.__iter__ "iterator.__iter__") and [`__next__()`](stdtypes.xhtml#iterator.__next__ "iterator.__next__") methods. See also the definition of [iterator](../glossary.xhtml#term-iterator). *class* `collections.abc.``Reversible`ABC for iterable classes that also provide the [`__reversed__()`](../reference/datamodel.xhtml#object.__reversed__ "object.__reversed__")method. 3\.6 新版功能. *class* `collections.abc.``Generator`ABC for generator classes that implement the protocol defined in [**PEP 342**](https://www.python.org/dev/peps/pep-0342) \[https://www.python.org/dev/peps/pep-0342\] that extends iterators with the [`send()`](../reference/expressions.xhtml#generator.send "generator.send"), [`throw()`](../reference/expressions.xhtml#generator.throw "generator.throw") and [`close()`](../reference/expressions.xhtml#generator.close "generator.close") methods. See also the definition of [generator](../glossary.xhtml#term-generator). 3\.5 新版功能. *class* `collections.abc.``Sequence`*class* `collections.abc.``MutableSequence`*class* `collections.abc.``ByteString`ABCs for read-only and mutable [sequences](../glossary.xhtml#term-sequence). Implementation note: Some of the mixin methods, such as [`__iter__()`](../reference/datamodel.xhtml#object.__iter__ "object.__iter__"), [`__reversed__()`](../reference/datamodel.xhtml#object.__reversed__ "object.__reversed__") and `index()`, make repeated calls to the underlying [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__") method. Consequently, if [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__") is implemented with constant access speed, the mixin methods will have linear performance; however, if the underlying method is linear (as it would be with a linked list), the mixins will have quadratic performance and will likely need to be overridden. 在 3.5 版更改: The index() method added support for *stop* and *start*arguments. *class* `collections.abc.``Set`*class* `collections.abc.``MutableSet`ABCs for read-only and mutable sets. *class* `collections.abc.``Mapping`*class* `collections.abc.``MutableMapping`ABCs for read-only and mutable [mappings](../glossary.xhtml#term-mapping). *class* `collections.abc.``MappingView`*class* `collections.abc.``ItemsView`*class* `collections.abc.``KeysView`*class* `collections.abc.``ValuesView`ABCs for mapping, items, keys, and values [views](../glossary.xhtml#term-dictionary-view). *class* `collections.abc.``Awaitable`ABC for [awaitable](../glossary.xhtml#term-awaitable) objects, which can be used in [`await`](../reference/expressions.xhtml#await)expressions. Custom implementations must provide the [`__await__()`](../reference/datamodel.xhtml#object.__await__ "object.__await__")method. [Coroutine](../glossary.xhtml#term-coroutine) objects and instances of the [`Coroutine`](#collections.abc.Coroutine "collections.abc.Coroutine") ABC are all instances of this ABC. 注解 In CPython, generator-based coroutines (generators decorated with [`types.coroutine()`](types.xhtml#types.coroutine "types.coroutine") or [`asyncio.coroutine()`](asyncio-task.xhtml#asyncio.coroutine "asyncio.coroutine")) are *awaitables*, even though they do not have an [`__await__()`](../reference/datamodel.xhtml#object.__await__ "object.__await__") method. Using `isinstance(gencoro, Awaitable)` for them will return `False`. Use [`inspect.isawaitable()`](inspect.xhtml#inspect.isawaitable "inspect.isawaitable") to detect them. 3\.5 新版功能. *class* `collections.abc.``Coroutine`ABC for coroutine compatible classes. These implement the following methods, defined in [协程对象](../reference/datamodel.xhtml#coroutine-objects): [`send()`](../reference/datamodel.xhtml#coroutine.send "coroutine.send"), [`throw()`](../reference/datamodel.xhtml#coroutine.throw "coroutine.throw"), and [`close()`](../reference/datamodel.xhtml#coroutine.close "coroutine.close"). Custom implementations must also implement [`__await__()`](../reference/datamodel.xhtml#object.__await__ "object.__await__"). All [`Coroutine`](#collections.abc.Coroutine "collections.abc.Coroutine") instances are also instances of [`Awaitable`](#collections.abc.Awaitable "collections.abc.Awaitable"). See also the definition of [coroutine](../glossary.xhtml#term-coroutine). 注解 In CPython, generator-based coroutines (generators decorated with [`types.coroutine()`](types.xhtml#types.coroutine "types.coroutine") or [`asyncio.coroutine()`](asyncio-task.xhtml#asyncio.coroutine "asyncio.coroutine")) are *awaitables*, even though they do not have an [`__await__()`](../reference/datamodel.xhtml#object.__await__ "object.__await__") method. Using `isinstance(gencoro, Coroutine)` for them will return `False`. Use [`inspect.isawaitable()`](inspect.xhtml#inspect.isawaitable "inspect.isawaitable") to detect them. 3\.5 新版功能. *class* `collections.abc.``AsyncIterable`ABC for classes that provide `__aiter__` method. See also the definition of [asynchronous iterable](../glossary.xhtml#term-asynchronous-iterable). 3\.5 新版功能. *class* `collections.abc.``AsyncIterator`ABC for classes that provide `__aiter__` and `__anext__`methods. See also the definition of [asynchronous iterator](../glossary.xhtml#term-asynchronous-iterator). 3\.5 新版功能. *class* `collections.abc.``AsyncGenerator`ABC for asynchronous generator classes that implement the protocol defined in [**PEP 525**](https://www.python.org/dev/peps/pep-0525) \[https://www.python.org/dev/peps/pep-0525\] and [**PEP 492**](https://www.python.org/dev/peps/pep-0492) \[https://www.python.org/dev/peps/pep-0492\]. 3\.6 新版功能. These ABCs allow us to ask classes or instances if they provide particular functionality, for example: ``` size = None if isinstance(myvar, collections.abc.Sized): size = len(myvar) ``` Several of the ABCs are also useful as mixins that make it easier to develop classes supporting container APIs. For example, to write a class supporting the full [`Set`](#collections.abc.Set "collections.abc.Set") API, it is only necessary to supply the three underlying abstract methods: [`__contains__()`](../reference/datamodel.xhtml#object.__contains__ "object.__contains__"), [`__iter__()`](../reference/datamodel.xhtml#object.__iter__ "object.__iter__"), and [`__len__()`](../reference/datamodel.xhtml#object.__len__ "object.__len__"). The ABC supplies the remaining methods such as [`__and__()`](../reference/datamodel.xhtml#object.__and__ "object.__and__") 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 ``` Notes on using [`Set`](#collections.abc.Set "collections.abc.Set") and [`MutableSet`](#collections.abc.MutableSet "collections.abc.MutableSet") as a mixin: 1. Since some set operations create new sets, the default mixin methods need a way to create new instances from an iterable. The class constructor is assumed to have a signature in the form `ClassName(iterable)`. That assumption is factored-out to an internal classmethod called `_from_iterable()` which calls `cls(iterable)` to produce a new set. If the [`Set`](#collections.abc.Set "collections.abc.Set") mixin is being used in a class with a different constructor signature, you will need to override `_from_iterable()`with a classmethod that can construct new instances from an iterable argument. 2. To override the comparisons (presumably for speed, as the semantics are fixed), redefine [`__le__()`](../reference/datamodel.xhtml#object.__le__ "object.__le__") and [`__ge__()`](../reference/datamodel.xhtml#object.__ge__ "object.__ge__"), then the other operations will automatically follow suit. 3. The [`Set`](#collections.abc.Set "collections.abc.Set") mixin provides a `_hash()` method to compute a hash value for the set; however, [`__hash__()`](../reference/datamodel.xhtml#object.__hash__ "object.__hash__") is not defined because not all sets are hashable or immutable. To add set hashability using mixins, inherit from both [`Set()`](#collections.abc.Set "collections.abc.Set") and [`Hashable()`](#collections.abc.Hashable "collections.abc.Hashable"), then define `__hash__ = Set._hash`. 参见 - [OrderedSet recipe](https://code.activestate.com/recipes/576694/) \[https://code.activestate.com/recipes/576694/\] for an example built on [`MutableSet`](#collections.abc.MutableSet "collections.abc.MutableSet"). - For more about ABCs, see the [`abc`](abc.xhtml#module-abc "abc: Abstract base classes according to PEP 3119.") module and [**PEP 3119**](https://www.python.org/dev/peps/pep-3119) \[https://www.python.org/dev/peps/pep-3119\]. ### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](heapq.xhtml "heapq --- 堆队列算法") | - [上一页](collections.xhtml "collections --- 容器数据类型") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [Python 标准库](index.xhtml) » - [数据类型](datatypes.xhtml) » - $('.inline-search').show(0); | © [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。