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

查看:128
本文介绍了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 __()

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

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天全站免登陆