python 设计模式-迭代器模式

mac2022-06-30  23

迭代器是一种很常用的设计模式,python 在语言层面也对迭代器进行了友好的支持,我前面有一篇介绍迭代器和可迭代对象的文章,初学者可以先了解下概念,这里主要通过代码示例进行说明。

#!/usr/bin/env python #coding: utf-8 class ProductLst: def __init__(self): self._product_lst = [] self._idx = -1 def add(self, product): self._product_lst.append(product) def __iter__(self): self._idx = -1 return self def __next__(self): self._idx += 1 if self._idx == len(self._product_lst): raise StopIteration return self._product_lst[self._idx] if __name__ == '__main__': ps = ProductLst() ps.add('pa') ps.add('pb') ps.add('pc') for p in ps: print(p)

输出:

pa pb pc

我们只要在需要迭代的对象上定义__next__方法,在for循环的时候会自动进行迭代遍历。

最新回复(0)