class Fib: def __init__(self): self.a=0 self.b=1 def __next__(self): self.a,self.b=self.b,self.a+self.b return self.a def __iter__(self): return self fib=Fib() for i in fib: if i<1000: print(i) else: break
In [1]: it=iter([x for x in range(100)]) In [2]: next(it) Out[2]: 0 In [3]: next(it) Out[3]: 1
class TestIterator: value = 0 def __next__(self): self.value += 1 if self.value > 10: raise StopIteration return self.value def __iter__(self): return self it=TestIterator() print(list(it))
运行结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
原文:https://www.cnblogs.com/Kerryworld/p/10810454.html