python中的iterator介绍及应用场景

本文深入解析Python迭代器的概念,介绍其工作原理与实现方法。通过具体示例展示如何创建自定义迭代器,包括__iter__()和next()方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        迭代器作为PY编程中比较常见的一个概念,也经常被我们所提及。然而若想深入到其内部了解其来龙去脉却也一时难以搞懂,恰巧群里面一个兄弟提及了这样一个问题,特来深入了解一下,并和大家分享出来。(注意:我本人一直在Version2.7上游离,所以若非特别注明,所有相关博客内容都是建立在这个版本上的)

原文及理解

New in version 2.2.
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always supportthe iteration methods.
(从版本2.2开始,python就支持利用容器来实现迭代的功能,是利用两个方法来实现的。这两个方法是为了让用户自定义的class能支持迭代.......)


The iterator objects themselves are required to support the following twomethods, which together form the iterator protocol:
iterator.__iter__()
      Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.
iterator.next()
      Return the next item from the container. If  there are no further items, raise the StopIteration exception. This method corresponds to thetp_iternext slot of the type structure for Python objects in thePython/C API.

(可迭代对象必须包含如下两个源自迭代协议中要求的方法:__iter__()和next()。__iter__()返回的是可迭代对象本身,这样就可以使此对象在for...in...语句中使用。另外,这个方法对应Python/C API中的......;而next()方法则返回容器的下一个item,若没有下一个item的话,就会引发StopIteration异常......)


举例

            应用场景:在一个包含有列表对象的容器对象上执行迭代操作

我们自定义一个类方法来获得一个等比数列,并分别定义出__iter__()和next()方法。按照上面的说法,我们需要在__iter__()中返回类本身,即“return self”,在next()方法中,我们定义每一个要返回的item,即“前一个数乘2后返回”。

#!usr/bin/env python
# -*- coding:utf-8 -*-

class MyIterator(object):
    """Show a iterator example which shows all items less than 100 and greater than 2in a geometric progression.
        a user-defined CLASS inheriteded from type object
        Args:
            x: a default integer:2, defines the begging parameter
            xmax:a default integer:100, defines the ending parameter
        Returns:
            obviously, it could have been an iterator object as expected.
        Raise:
            An error occurred while no further iterator items
    """
    def __init__(self, x=2, xmax=100):
        self.__mul,self.__x = x,x
        self.__xmax = xmax
        
    def __iter__(self):
        '''return the iterator object itself'''
        return self
    
    def next(self):
        if self.__x and self.__x != 1:
            self.__mul = self.__mul * self.__x
            if self.__mul <= self.__xmax:
                return self.__mul
            else:
                raise StopIteration
        else:
            raise StopIteration
        
if __name__ == "__main__":
    m_iter = MyIterator()
    #for more invisiable of an iterator, we use print derectly instead
    #for itm in m_iter:
    #    print itm
    print next(m_iter)
    print next(m_iter)
    print next(m_iter)
    print next(m_iter)
    print next(m_iter)

运行结果:

4
8
16
32
64


注意

  • iterator是一个消耗型的容器,上面的示例中,‘64’是最后一个数字,如果我们再第六次调用next()方法,则会引发StopIteration异常,感兴趣的自己试一下。
  • 在python3.X中,上述next()不再奏效,需要换成__next__()才行;同样,在python2.7中__next__()也是不奏效的,具体情况大家自行试验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值