Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time the next() is called, the generator resumes where it left-off (it remembers all the data values and which statement was last executed). An example shows that generators can be trivially easy to create:
发生器是创建迭代器的简单而强大的工具。它们写起来就像是正则函数,需要返回数据的时候使用 yield 语句。每次 next() 被调用时,生成器回复它脱离的位置(它记忆语句最后一次执行的位置和所有的数据值)。以下示例演示了发生器可以很简单的创建出来:
>>> def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] >>> for char in reverse('golf'): print char f l o g
Anything that can be done with generators can also be done with class based iterators as described in the previous section. What makes generators so compact is that the __iter__() and next() methods are created automatically.
前一节中描述了基于类的迭代器,它能作的每一件事发生器也能作到。因为自动创建了 __iter__() 和 next() 方法,发生器显得如此简洁。
Another key feature is that the local variables and execution state
are automatically saved between calls. This made the function easier to write
and much more clear than an approach using class variables like
self.index
and self.data
.
另外一个关键的功能是两次调用之间的局部变量和执行情况都自动保存了下来。这样函数编写起来就比手动调用
self.index
和 self.data
这样的类变量容易的多。
In addition to automatic method creation and saving program state, when generators terminate, they automatically raise StopIteration. In combination, these features make it easy to create iterators with no more effort than writing a regular function.
除了创建和保存程序状态的自动方法,当发生器终结时,还会自动抛出 StopIteration 异常。综上所述,这些功能使得编写一个正则函数成为创建迭代器的最简单方法。