1.迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个Stopiteration异常,以终止迭代
2.可迭代对象:实现了迭代器协议的对象(如何实现:对象内部定义一个__iter__方法)
class Foo: def __init__(self,n): self.n=n def __iter__(self): return self def __next__(self): if self.n == 13: raise StopIteration(‘终止了‘) self.n+=1 return self.n # l=list(‘hello‘) # for i in l: # print(i) f1=Foo(10) print(f1.__next__()) #11 print(f1.__next__()) #12 print(f1.__next__()) #13 print(f1.__next__()) #StopIteration: 终止了 # for i in f1: # obj=iter(f1)------------>f1.__iter__() # print(i) #obj.__next_()
class Fib: def __init__(self): self._a=1 self._b=1 def __iter__(self): return self def __next__(self): if self._a>100: raise StopIteration(‘终止‘) self._a,self._b=self._b,self._a+self._b return self._a f1=Fib() print(next(f1)) print(next(f1)) print(next(f1)) print(next(f1)) print(next(f1)) print(‘==============‘) for i in f1: print(i) # 1 # 2 # 3 # 5 # 8 # ============== # 13 # 21 # 34 # 55 # 89 # 144
原文:https://www.cnblogs.com/wuweixiong/p/10616569.html