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

473次阅读
没有评论

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

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

python迭代器协议方法

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

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

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

python迭代器协议实例

class Counter(object):
def __init__(self, low, high):
self.current = low
self.high = high
 
def __iter__(self):
return self
 
def __next__(self):
#返回下一个值直到当前值大于 high
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-04-02发表,共计431字。
新手QQ群:570568346,欢迎进群讨论 Python51学习