python笔记:迭代器 1 原理指实现系统的迭代接口,这样,我们自己的对象也能使用系统的 for in 来进行迭代循环,是不是很酷!在每次迭代之时,类的内部状态都发生了变化,所以我们的next函数的实现重点在于,引起类的内部状态变化,使之能记录上下文。2 实现# -*- coding: utf-8 -*- #迭代打印“张三,李四,王五” class Employee(object): def __init__(self): self._current = "" self.namea = u"张三" self.nameb = u"李四" self.namec = u"王五" def __iter__(self): self._current = self.namea return self def __next__(self): if self._current == self.namea: self._current = self.nameb return self.namea elif self._current == self.nameb: self._current = self.namec return self.nameb elif self._current == self.namec: self._current = "" return self.namec elif self._current == "": raise StopIteration for item in Employee(): print(item) for item in Employee(): print(item)更多资料http://www.cnblogs.com/huxi/archive/2011/07/01/2095931.html 来自 大脸猫 写于 2016-05-17 15:09 -- 更新于2020-10-19 13:06 -- 0 条评论