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.
相关文章