• 技术文章 >Python技术 >Python基础教程

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

    小妮浅浅小妮浅浅2021-08-10 09:17:45原创2038

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

    方法

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

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

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

    实例

    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迭代器协议支持的两种方法,希望对大家有所帮助。更多ps学习指路:ps教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python迭代器协议
    品易云
    上一篇:python线程安全的介绍及解决方法 下一篇:python中chardet库的安装和导入

    相关文章推荐

    • python迭代器如何实现• python迭代器和生成器区别是什么• python迭代器是什么意思• 你知道python迭代器和生成器的区别吗?• python迭代器与生成器用途是什么• python迭代器中Yield方法怎么用?• python迭代器是什么• Python迭代器的基本方法有几个• python迭代器如何转换为生成器• python迭代器中的函数整理• python迭代器怎样自定义类

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网