__iter__
当您尝试遍历类实例时调用的是什么:
>>> class Foo(object):... def __iter__(self):... return (x for x in range(4))... >>> list(Foo())[0, 1, 2, 3]
__next__
是在返回的对象上调用的内容
__iter__
(在python2.x上
next
,不是
__next__
,我一般都对它们都使用别名,以便代码可以与其中任何一个一起使用…):
class Bar(object): def __init__(self): self.idx = 0 self.data = range(4) def __iter__(self): return self def __next__(self): self.idx += 1 try:return self.data[self.idx-1] except IndexError:self.idx = 0raise StopIteration # Done iterating. next = __next__ # python2.x compatibility.