python迭代器协议支持的两种方法

python迭代器协议支持的两种方法

迭代协议是指容器类需要包含一种特殊的方法,即__iter__()方法。

方法

python迭代器(_Iterators_)erators_)对象需要支持以下两种方法。

1、iter(),返回迭代对象本身。它用于for和in。

2、next(),返回迭代器的下一个值。若无下一个值可返回,则应抛出StopIteration异常。

实例

classCounter(object):
def__init__(self,low,high):
self.current=low
self.high=high

def__iter__(self):
returnself

def__next__(self):
#返回下一个值直到当前值大于high
ifself.current>self.high:
raiseStopIteration
else:
self.current+=1
returnself.current-1

以上就是python迭代器协议支持的两种方法,希望对大家有所帮助。更多ps学习指路:ps教程