叠代器協議
阿新 • • 發佈:2019-03-28
none 執行 return 斐波那契 斐波那契數 top 叠代器協議 圖片 ext
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(‘View Code終止了‘) 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
叠代器協議