next和iter可迭代协议
python中,对象中实现了__iter__方法就是可迭代对象
实现了__next__方法就是迭代器
代码示例
from collections import Iterator,Iterable
class Foo:
def __next__(self):
pass
def __iter__(self):
pass
f= Foo()
print(isinstance(f,Iterator))
print(isinstance(f,Iterable))
执行结果
True
True
实现一个斐波那契数列
代码:
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
f = Fib()
print(next(f))
print(next(f))
print(next(f))
print(next(f))
执行结果
1
1
2
3
模拟range函数
class RANGE:
def __init__(self,start,stop,step=1):
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
if self.start >= self.stop:
raise StopIteration
res = self.start
self.start +=self.step
return res
for i in RANGE(2,10,2):
print(i)
执行结果
2
4
6
8