__iter__和__next__实现迭代器协议
Posted manuel
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了__iter__和__next__实现迭代器协议相关的知识,希望对你有一定的参考价值。
__iter__()将对象转换为可迭代对象,__next__()返回实现迭代
#_*_coding:utf-8_*_ __author__ = ‘Linhaifeng‘ class Foo: def __init__(self,x): self.x=x def __iter__(self): return self def __next__(self): n=self.x self.x+=1 return self.x f=Foo(3) for i in f: print(i)
class Foo: def __init__(self,start,stop): self.num=start self.stop=stop def __iter__(self): return self def __next__(self): if self.num >= self.stop: raise StopIteration n=self.num self.num+=1 return n f=Foo(1,5) from collections import Iterable,Iterator print(isinstance(f,Iterator)) for i in Foo(1,5): print(i)
斐波那契数列:
#1,1,2,3,5,8,13,21... class Foo: def __init__(self,star,end): self.mid = 0 self.star = star self.end = end def __iter__(self): return self def __next__(self): self.mid,self.star = self.star,self.mid+self.star if self.star >= self.end: raise StopIteration return self.star f1=Foo(1,1000) for i in f1: print(i)
1
以上是关于__iter__和__next__实现迭代器协议的主要内容,如果未能解决你的问题,请参考以下文章