__next__和__iter__实现迭代器协议

时间:2023-12-05 16:21:50

---恢复内容开始---

#_*_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)
复制代码
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='')

---恢复内容结束---