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

    Python yield实现迭代器协议

    小妮浅浅小妮浅浅2021-09-06 09:58:46原创2144

    说明

    1、yield实现迭代器协议的两种方法__iter__和next(Python 2) 或__next__(Python 3)。

    2、这两种方法都使对象成为迭代器。

    可以使用模块中的Iterator抽象基类对它进行类型检查collections。

    实例

    >>> def func():
    ...     yield 'I am'
    ...     yield 'a generator!'
    ...
    >>> type(func)                 # A function with yield is still a function
    <type 'function'>
    >>> gen = func()
    >>> type(gen)                  # but it returns a generator
    <type 'generator'>
    >>> hasattr(gen, '__iter__')   # that's an iterable
    True
    >>> hasattr(gen, 'next')       # and with .next (.__next__ in Python 3)
    True

    以上就是Python yield实现迭代器协议的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:pythonyield
    品易云
    上一篇:Python yield关键字的应用限制 下一篇:python列表删除项目的方法

    相关文章推荐

    • 什么是网络协议• python中的去除重复项的操作• python中少见的函数map()和partial()• python的sort()排序方法• Python中的文件读写-理论知识

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网