python的枚举器类需要实现__iter__魔法方法返回枚举器实例,还需要实现一个next方法,在枚举到末尾时抛出StopIteration异常表示枚举结束。如下简单示例:
class SimpleIterator: def __init__(self,maxvalue): self.current = 0 self.max = maxvalue def next(self): result = self.current self.current += 1 if result == self.max : raise StopIteration() return result def __iter__(self): return self li = list(SimpleIterator(5)) print li
yield生成器实现示例如下:
def yield_test(maxvalue): i = -1 while i < maxvalue-1: i += 1 yield i for i in yield_test(10): print i