将一个容器通过iter()函数处理后,就变成了迭代器。迭代器有2个魔法方法__iter__、__next__,一个迭代器必须实现__iter__,这个方法实际上是返回迭代器本身(return self),而__next__决定了迭代器迭代的规则。
class Fibs: def __init__(self, n=10): self.a = 0 self.b = 1 self.n = n def __iter__(self): return self def __next__(self): self.a, self.b = self.b, self.a + self.b if self.a > self.n: raise StopIteration return self.a >>> fibs = Fibs(100) >>> for each in fibs: print(each) 1 1 2 3 5 8 13 21 34 55 89 >>>