Skip to main content
 首页 » 编程设计

python之在 Python 中将类型定义为 (1) 序列 (2) 可迭代类型的确切规范是什么

2025年05月04日14insus

类定义中必须实现哪些方法才能被视为序列类型和可迭代类型?如果它们有正式定义,您是否也可以提供对 PEP 或定义它的其他文档的引用?

请您参考如下方法:

来自 the glossary :

一个可迭代对象是:

A object with an __iter__() or __getitem__() method. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict and file. When an iterable object is passed as an argument to the builtin function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values.

迭代器是:

An iterable which has a next() method. Iterators are required to have an __iter__() method that returns the iterator object itself. An iterator is good for one pass over the set of values.

一个序列是:

An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a len() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and unicode. Note that dict also supports __getitem__() and __len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers.