迭代协议是指容器类需要包含一种特殊的方法,即__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
查看更多关于python迭代器协议支持的两种方法的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did181007