Skip to main content
 首页 » 编程设计

python之解释 : Every generator is an iterator, 而不是反之

2025年02月15日8lautakyan007

我知道什么是迭代器和生成器。我知道迭代协议(protocol),我可以创建两者。我到处都读到下面这行:“每个生成器都是一个迭代器,但反之则不然。”我理解第一部分,但我不理解“反之亦然”部分。生成器对象有什么是任何简单迭代器对象所没有的?

我读了this question但它没有解释为什么迭代器不是生成器。解释差异的仅仅是语法 yield 吗?

提前致谢。

请您参考如下方法:

I know what's iterator, what's generator, what's iteration protocol, how to create both.

什么是迭代器?

根据词汇表,iterator是“代表数据流的对象”。它有一个返回自身的 __iter__() 方法,还有一个 next() 方法(在 Python 3 中是 __next__())。 next-method 负责返回一个值,推进迭代器,并在完成时引发 StopIteration。

什么是生成器?

生成器是包含 yield 的常规 Python 函数。当被调用时,它返回一个生成迭代器(许多迭代器中的一种)。

如何创建生成器和迭代器的示例

生成器示例:

>>> def f(x):           # "f" is a generator 
        yield x 
        yield x**2 
        yield x**3 
 
>>> g = f(10)           # calling "f" returns a generator-iterator  
>>> type(f)             # "f" is a regular python function with "yield" 
<type 'function'> 
>>> type(g)                  
<type 'generator'> 
>>> next(g)             # next() gets a value from the generator-iterator 
10 
>>> next(g) 
100 
>>> next(g) 
1000 
>>> next(g)             # iterators signal that they are done with an Exception 
 
Traceback (most recent call last): 
  File "<pyshell#11>", line 1, in <module> 
    next(g) 
StopIteration 
>>> dir(g)              # generator-iterators have next() and \__iter__ 
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw'] 

使用类的迭代器:

>>> class Powers:       # "Powers" is a class 
        def __init__(self, base): 
            self.base = base 
            self.exp = 0 
        def __iter__(self): 
            return self 
        def next(self): 
            self.exp += 1 
            if self.exp > 3: 
                raise StopIteration 
            return self.base ** self.exp 
 
>>> g = Powers(10)      # calling "Powers" returns an iterator 
>>> type(Powers)        # "Power" is a regular python class 
<type 'classobj'> 
>>> type(g)             # "g" is a iterator instance with next() and __iter__() 
<type 'instance'>    
>>> next(g)             # next() gets a value from the iterator 
10 
>>> next(g) 
100 
>>> next(g) 
1000 
>>> next(g)             # iterators signal that they are done with an Exception 
 
Traceback (most recent call last): 
  File "<pyshell#34>", line 1, in <module> 
    next(g) 
StopIteration 

来自序列示例的迭代器:

>>> s = 'cat'                
>>> it = iter(s)            # creates an "iterator" from a sequence  
>>> type(s)                 # "s" is a string which is "iterable" 
<type 'str'> 
>>> type(it)                # An "iterator" with next() and __iter__() 
<type 'iterator'> 
>>> next(it) 
'c' 
>>> next(it) 
'a' 
>>> next(it) 
't' 
>>> next(it) 
 
Traceback (most recent call last): 
  File "<pyshell#43>", line 1, in <module> 
    next(it) 
StopIteration 

比较与结论

迭代器是表示数据流的对象。它有一个 __iter__() 方法和一个 next() 方法。

有几种制作迭代器的方法:

1) 调用生成器(使用 yield 的常规 python 函数) 2) 实例化一个具有 __iter__() 方法和 next() 方法的类。

由此,您可以看到生成器只是制作迭代器的众多方法之一(还有其他方法:itertools、常规函数上的 iter() 和哨兵,等)。