品易云推流 关闭
文章详情页
文章 > Python基础教程 > Python yield实现迭代器协议

Python yield实现迭代器协议

Python yield

头像

小妮浅浅

2021-09-06 09:58:463136浏览 · 0收藏 · 0评论

说明

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电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图