python的枚舉器類須要實現__iter__魔法方法返回枚舉器實例,還須要實現一個next方法,在枚舉到末尾時拋出StopIteration異常表示枚舉結束。以下簡單示例:python
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