__next__,__iter__实现迭代器,斐波那契数列
迭代器__next__,__iter__
基于__next__和__iter__方法实现的迭代器
class Foo: def __init__(self,n): self.n = n def __iter__(self): return self def __next__(self): if self.n==100: raise StopIteration('终 止') #到100就终止,for循环并且不会抛出异常 self.n+=1 return self.n f1 = Foo(10) print(f1.__next__()) #这样取值,就会抛异常 for i in f1: print(i)
斐波那契数列
class Fib: def __init__(self): self._a=0 self._b=1 def __iter__(self): return self def __next__(self): self._a,self._b=self._b,self._a + self._b return self._a f1=Fib() print(f1.__next__()) print(next(f1)) print(next(f1)) for i in f1: if i > 100: break print('%s ' %i,end='')