Python 的迭代器协议到底是什么? [英] What exactly is Python's iterator protocol?

查看:22
本文介绍了Python 的迭代器协议到底是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有客观的定义吗?它是作为python源代码的片段实现的吗?如果是这样,有人可以生成确切的代码行吗?是否所有语言都有自己的for"语句迭代器协议?

Is there an objective definition? Is it implemented as a fragment of python's source code? If so, could someone produce the exact code lines? Have all languages with, say, a 'for' statement iterator protocols of their own?

推荐答案

位于 这里在文档中:

需要为容器对象定义一个方法来提供迭代支持:

One method needs to be defined for container objects to provide iteration support:

container.__iter__()

返回一个迭代器对象.该对象需要支持下面描述的迭代器协议.如果容器支持不同类型的迭代,则可以提供额外的方法来专门为这些迭代类型请求迭代器.(支持多种迭代形式的对象的一个​​示例是支持广度优先和深度优先遍历的树结构.)此方法对应于 Python 对象类型结构的 tp_iter 槽在 Python/C API 中.

Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

迭代器对象本身需要支持以下两种方法,它们共同构成了迭代器协议:

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

iterator.__iter__()

返回迭代器对象本身.这是允许容器和迭代器与 for 和 in 语句一起使用的必要条件.此方法对应于 Python/C API 中 Python 对象的类型结构的 tp_iter 槽.

Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

iterator.__next__()

从容器中返回下一个项目.如果没有其他项目,则引发 StopIteration 异常.此方法对应于 Python/C API 中 Python 对象的类型结构的 tp_iternext 槽.

Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

这篇关于Python 的迭代器协议到底是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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