每天学点Python之Iterator

来源:互联网 发布:宝马x5和奔驰gle 知乎 编辑:程序博客网 时间:2024/05/22 16:46

每天学点Python之Iterator


我们经常需要遍历一个对象中的元素,在Python中这种功能是通过迭代器来实现的。

原理

每一个迭代器可以通过反复调用迭代器的__next__()方法来返回创建该迭代器的对象中的后继值。当没有可用数据时,产生一个StopInteration异常。此时,迭代器对象被耗尽,之后再调用 __next__()方法只会再次产生StopInteration异常。需要访问的对象要求包含一个__iter__()方法,用于返回迭代器对象,如果对象就实现了迭代器方法,就可以返回对象本身。

使用

我们可以通过调用iter()方法来返回对象的迭代器:

>>> i = iter("hello")>>> i.__next__()'h'>>> next(i)'e'>>> next(i)'l'>>> next(i)'l'>>> next(i)'o'>>> next(i)Traceback (most recent call last):  File "<input>", line 1, in <module>StopIteration

对于Python中常见的一些数据类型,如元组、列表、字典等都已经自己实现了迭代器功能,这使得它们能在for循环中正常工作:

>>> for i in (2,3,1):...     print(i)...     231

自定义

如果我们要求自定义访问对象中的数据,那该如何做呢,我们需要实现__iter()__和__next()__方法,下面我们给出自己的对象,实现一个简易的计时器功能:

class CountDown:    def __init__(self, start):        self.count = start    def __iter__(self):        return self    def __next__(self):        if self.count <= 0:            raise StopIteration        r = self.count        self.count -= 1        return rif __name__ == "__main__":    for time in CountDown(3):        print(time)输出:3 2 1
0 0
原创粉丝点击