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

    python StopIteration异常的使用

    小妮浅浅小妮浅浅2021-09-26 09:51:57原创4718

    1、StopIteration异常用于完成标识迭代,防止循环。

    2、__next__()完成指定循环次数,触发StopIteration异常结束迭代。

    实例

    class MyNumbers:
        def __iter__(self):
            self.a = 1
            return self
        def __next__(self):
            if self.x < 20:
                x = self.a
                self.a += 1
                return x
            else:
                raise StopIteration
    myclass = MyNumbers()
    myiter = iter(myclass)
     
    for x in myiter:
        print(x)

    以上就是python StopIteration异常的使用,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:python stopiteration
    品易云
    上一篇:python迭代器的要点整理 下一篇:python生成器的调用理解

    相关文章推荐

    • python poetry如何创建项目• python poetry创建虚拟环境• python poetry如何安装依赖• python中flake8是什么• python中mypy是什么• python创建链表的两种形式• python面向过程的优缺点• python面向对象编程的优缺点• python面向对象设计和面向对象编程的理解• python类属性和实例属性的区别

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网