模块`collections`中的其他26个元素

Alg*_*bra 2 python python-3.x

我正在努力深入挖掘并在学习Python方面更上一层楼.

在尝试学习collections模块的所有内容时,我在探索模块的每个角落时遇到了问题.在在线文档中help(collections),它引入了9种专用容器数据类型,见 8.3.集合 - 容器数据类型:

['Counter', 'OrderedDict', 'defaultdict', 'deque',
 'namedtuple', 'ChainMap', 'UserDict', 'UserList', 'UserString']
Run Code Online (Sandbox Code Playgroud)

与该列表相比,文档中未指定其他26个,并且help()输出中的细节非常有限:

x = [ i for i in dir(collections) if not i.startswith('_')]
>>> list(enumerate(x, start=1))
[(1, 'AsyncGenerator'), (2, 'AsyncIterable'), (3, 'AsyncIterator'), (4, 'Awaitable'), (5, 'ByteString'), (6, 'Callable'), 
 (7, 'ChainMap'), (8, 'Collection'), (9, 'Container'), (10, 'Coroutine'), (11, 'Counter'), (12, 'Generator'), (13, 'Hashable'), (14, 'ItemsView'), (15, 'Iterable'), (16, 'Iterator'), 
 (17, 'KeysView'), (18, 'Mapping'), (19, 'MappingView'), (20, 'MutableMapping'), (21, 'MutableSequence'), (22, 'MutableSet'),
 (23, 'OrderedDict'), (24, 'Reversible'), (25, 'Sequence'), (26, 'Set'), (27, 'Sized'), (28, 'UserDict'), 
 (29, 'UserList'), (30, 'UserString'), (31, 'ValuesView'), 
 (32, 'abc'), (33, 'defaultdict'), (34, 'deque'), (35, 'namedtuple')]
Run Code Online (Sandbox Code Playgroud)

是否有必要投入时间探索其他26?

Mar*_*ers 6

您正在查看__all__模块的全局变量的导出列表.由于两个原因,此列表大于仅记录的对象.首先是它包括子模块; 在这种情况下collections.abc,此处列为abc.

第二个是为了向后兼容而添加了对象; 额外的名字来自collections.abc子模块.曾几何时,该模块不存在,并且这些对象collections在被移动之前就已经存在.导入该模块的名称collections以容纳仍从旧位置导入的代码.

在您链接的页面上记录:

在版本3.3中更改:将集合抽象基类移动到collections.abc模块.为了向后兼容,它们也继续在此模块中可见.

所以在那些26中,一个是子模块collections, collections.abc其余25个对象明确地用于支持移动到collections.abc模块的名称的向后兼容性.

如果您想了解其他对象,那么您会发现它们都记录在自己的位置.使用help(collections.abc)collections.abc模块文档.