迭代器模式(Iterator Pattern)

1 代码

今天的主角是迭代器模式。在python中,迭代器并不用举太多的例子,因为python中的迭代器应用实在太多了(不管是python还是其它很多的编程语言中,实际上迭代器都已经纳入到了常用的库或者包中)。而且在当前,也几乎没有人专门去开发一个迭代器,而是直接去使用list、string、set、dict等python可迭代对象,或者直接使用__iter__和next函数来实现迭代器。如下例:


In [3]:
lst=["hello Alice","hello Bob","hello Eve"]
lst_iter=iter(lst)
print (lst_iter)
print (lst_iter.__next__())
print (lst_iter.__next__())
print (lst_iter.__next__())
print (lst_iter.__next__())


<list_iterator object at 0x107127860>
hello Alice
hello Bob
hello Eve
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-3-e4740f8e7b01> in <module>()
      5 print (lst_iter.__next__())
      6 print (lst_iter.__next__())
----> 7 print (lst_iter.__next__())

StopIteration: 

在python对象的方法中,也可以轻易使用迭代器模式构造可迭代对象,如下例:


In [4]:
class MyIter(object):
    def __init__(self,n):
        self.index=0
        self.n=n
    def __iter__(self):
        return self
    def __next__(self):
        if self.index < self.n:
            value = self.index * 2
            self.index += 1
            return value
        else:
            raise StopIteration()

In [7]:
x_square = MyIter(10)
for x in x_square:
    print(x)


0
2
4
6
8
10
12
14
16
18