如果要达到多个迭代器的效果,__iter__()只需替迭代器定义新的状态对象,而不是返回self
class SkipIterator:
def __init__(self, wrapped):
self.wrapped = wrapped
self.offset = 0 def __next__(self):
if self.offset >= len(self.wrapped):
raise StopIteration
else:
item = self.wrapped[self.offset]
self.offset+=2
return item class SkipObject:
def __init__(self, wrapped):
self.wrapped = wrapped def __iter__(self):
return SkipIterator(self.wrapped) if __name__ == '__main__':
hhh = 'hahaha'
skipper = SkipObject(hhh)
for i in skipper:
print(i) I = iter(skipper)
print(next(I), next(I), next(I))
参考资料:Python学习手册