Python学习之基本数据类型 迭代器

4.5. Iterator Types

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.
翻译:Python的容器类支持迭代这个概念。它继承和使用两个独立的方法,这两个方法允许用户一些类来支持迭代。下面将要介绍的序列也支持迭代的方法。

One method needs to be defined for container objects to provide iteration support:
翻译:对于容器对象来说必须实现其中一个方法来支持迭代。

container. __iter__ ( )

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 thetp_iter slot of the type structure for Python objects in the Python/C API.
翻译:返回一个迭代对象,这个对象将支持下面描述的几种迭代协议。如果一个容器支持不同的迭代类型,可以添加额外的方法来满足对迭代方法有特殊要求的迭代类型。(比如:一个对象支持迭代器的多种格式,比如树形结构的广度优先遍历和深度优先遍历)这个方法对应着槽函数tp_iter 这种Python对象的数据结构。

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
翻译:迭代器对象它们都需要支持下面的两种方法。

iterator. __iter__ ( )

Return the iterator object itself. This is required to allow both containers and iterators to be used with the forand in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.
翻译:返回迭代器本身。这就需要容器和迭代器在for in 结构中使用。这个方法对应着Python对象的槽函数

iterator. __next__ ( )

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.
翻译:返回容器的下一个item。如果没有更多的item,就会抛出StopIteration异常。这个方法对应着Python对象的槽函数

Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.
翻译:Python定义了几种迭代器类型来支持迭代一般和制定的序列,字典等等特殊的类型。对于这些特殊的类型,迭代器并不是那么重要(不知道翻译的对不对)。

Once an iterator’s __next__() method raises StopIteration, it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.
翻译:一旦迭代器抛出了异常。。。。。


4.5.1. Generator Types

Python’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and __next__() methods. More information about generators can be found in the documentation for the yield expression.



猜你喜欢

转载自blog.csdn.net/rubikchen/article/details/80554829