标签:对象 turn 迭代器 offset code self 效果 学习 python
如果要达到多个迭代器的效果,__iter__()只需替迭代器定义新的状态对象,而不是返回self
1 class SkipIterator: 2 def __init__(self, wrapped): 3 self.wrapped = wrapped 4 self.offset = 0 5 6 def __next__(self): 7 if self.offset >= len(self.wrapped): 8 raise StopIteration 9 else: 10 item = self.wrapped[self.offset] 11 self.offset+=2 12 return item 13 14 15 class SkipObject: 16 def __init__(self, wrapped): 17 self.wrapped = wrapped 18 19 def __iter__(self): 20 return SkipIterator(self.wrapped) 21 22 23 if __name__ == ‘__main__‘: 24 hhh = ‘hahaha‘ 25 skipper = SkipObject(hhh) 26 for i in skipper: 27 print(i) 28 29 I = iter(skipper) 30 print(next(I), next(I), next(I))
参考资料:Python学习手册
标签:对象 turn 迭代器 offset code self 效果 学习 python
原文地址:http://www.cnblogs.com/fcyworld/p/6240323.html