Python的生成器和迭代器之间的区别 [英] Difference between Python's Generators and Iterators

查看:450
本文介绍了Python的生成器和迭代器之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

迭代器和生成器之间有什么区别?您将使用每种情况的一些示例将会有所帮助。

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.

推荐答案

iterator 是一个更通用的概念:任何对象的类具有 next 方法(Python 3中的 __ next __ )和 __ iter __ 执行返回自我的方法

iterator is a more general concept: any object whose class has a next method (__next__ in Python 3) and an __iter__ method that does return self.

每台发电机是一个迭代器,但反之亦然。通过在Python 2.5及更早版本中调用具有一个或多个 yield 表达式( yield 语句)的函数来构建生成器),是一个符合前一段迭代器定义的对象。

Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield expressions (yield statements, in Python 2.5 and earlier), and is an object that meets the previous paragraph's definition of an iterator.

您可能想要使用自定义迭代器,而不是生成器,当你需要一个具有一些复杂的状态维护行为的类,或者想要暴露除 next 之外的其他方法(和 __iter __ __ init __ )。大多数情况下,生成器(有时,对于足够简单的需求,生成器表达式)就足够了,并且编码更简单,因为状态维护(在合理的限制范围内)基本上是由你完成的框架暂停并恢复。

You may want to use a custom iterator, rather than a generator, when you need a class with somewhat complex state-maintaining behavior, or want to expose other methods besides next (and __iter__ and __init__). Most often, a generator (sometimes, for sufficiently simple needs, a generator expression) is sufficient, and it's simpler to code because state maintenance (within reasonable limits) is basically "done for you" by the frame getting suspended and resumed.

例如,生成器如:

def squares(start, stop):
    for i in range(start, stop):
        yield i * i

generator = squares(a, b)

或等效的生成器表达式(genexp)

or the equivalent generator expression (genexp)

generator = (i*i for i in range(a, b))

需要更多代码来构建自定义迭代器:

would take more code to build as a custom iterator:

class Squares(object):
    def __init__(self, start, stop):
       self.start = start
       self.stop = stop
    def __iter__(self): return self
    def next(self):
       if self.start >= self.stop:
           raise StopIteration
       current = self.start * self.start
       self.start += 1
       return current

iterator = Squares(a, b)

但是,当然,你可以轻松地提供 Squares 等级额外的方法,即

But, of course, with class Squares you could easily offer extra methods, i.e.

    def current(self):
       return self.start

如果您在申请中确实需要此类额外功能。

if you have any actual need for such extra functionality in your application.

这篇关于Python的生成器和迭代器之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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