可迭代對象
是指實(shí)現(xiàn)了內(nèi)置的iter方法的對象迭代器(iterator)
那么什么迭代器呢僚祷?它是一個(gè)帶狀態(tài)的對象,他能在你調(diào)用 next() 方法的時(shí)候返回容器中的下一個(gè)值,任何實(shí)現(xiàn)了 next() (python2中實(shí)現(xiàn) next() )方法的對象都是迭代器,至于它是如何實(shí)現(xiàn)的這并不重要。-
注意:一個(gè)對象既可以是迭代器也可以是可迭代對象
實(shí)例:class Fib: def __init__(self): self.prev=0 self.curr=1 def __iter__(self): return self def __next__(self): value=self.curr self.curr+=self.prev self.prev=value return value
也可以用生成器來實(shí)現(xiàn)
class FloatRange:
def __init__(self,start,end,step):
self.start=start
self.end=end
self.step=step
#正向迭代
def __iter__(self):
t=self.start
while t<=self.end:
yield t
t+=self.step
#反向迭代
def __reversed__(self):
t=self.end
while t>=self.start:
yield t
t-=self.step