生成器,迭代器和迭代器协议之间的区别

时间:2015-04-21 22:31:06

标签: python iterator syntactic-sugar

这个问题被多次询问,但我没有直接看到我的版本的答案,所以......

使用迭代器协议,如下面的例子,我可以创建像迭代器一样的对象,也像生成器一样。

  1. 对象级别的迭代器和生成器之间是否存在真正的区别?
  2. yield关键字只是python解释器的糖,用iterator协议创建类吗?
  3. 我可以用支持迭代器协议的类替换每个生成器(或协同例程)函数吗?
  4. 示例:

    def make_iterable():
        return [1, 2, 3, 4, 5]
    
    # This class behaves like a function above when iterating its instances.
    class IteratorBehave(object):
        def __init__(self):
            self.data = [1, 2, 3, 4, 5]
        def __iter__(self):
            class Iter(object):
                def __init__(self, data):
                    self.index = 0
                    self.data = data
                def next():
                    if self.index < len(self.data):
                        current = self.data[self.index]
                        self.index += 1
                        return current
                    raise StopIteration()
    
            return Iter(self.data)
    
    def make_generator():
        v = 1
        while v <= 5:
            yield v
            v += 1  
    
    # This class behaves like a generator function above when iterating its instances.
    class GeneratorBehave(object):
        def __init__(self):
            self.max = 5
        def __iter__(self):
            class Gen(object):
                def __init__(self, max):
                    self.current = 1
                    self.max = max
                def next():
                    if self.current <= self.max:
                        current = self.current
                        self.current += 1
                        return current
                    raise StopIteration()
            return Gen(self.max)
    

0 个答案:

没有答案