什么是一个类型的精确规范是一个(1)序列(2)Python中的可迭代类型? [英] What are exact specification for a type to be a (1) sequence (2) iterable type in Python?

查看:209
本文介绍了什么是一个类型的精确规范是一个(1)序列(2)Python中的可迭代类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类定义中必须实现什么方法,以便它可以被视为序列类型和可迭代类型?

What methods must be implemented in a class definition so that it can be considered as a sequence type and an iterable type? And if there's a formal definition for them can you also provide a reference to PEP or another document where it is defined?

推荐答案

如果有正式的定义,你还可以提供对PEP或其他文档的引用。 词汇

From the glossary:

可迭代的是:


具有 __ iter __() __ getitem __()方法。
iterables的示例包括所有序列类型(如list,str和tuple)
和一些非序列类型,如dict和file。当可迭代的
对象作为参数传递给内置函数iter()时,
返回对象的迭代器。这个迭代器对于一个值
的值是有好处的。

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.

迭代器是:


一个迭代,它有一个next()方法。迭代器需要有返回迭代器对象本身的
__ iter __()方法。
迭代器适用于对一组值的一次传递。

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.

序列是:


一个迭代器,通过 __ getitem __()特殊方法支持使用整数
索引的高效元素访问并定义一个len()
方法,返回序列的长度。一些内置的序列
类型是list,str,tuple和unicode。注意,dict还支持
__ getitem __() __ len __(),但被认为是映射, b $ b比序列,因为查找使用任意不可变的键
而不是整数。

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.

这篇关于什么是一个类型的精确规范是一个(1)序列(2)Python中的可迭代类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆