当前位置: 首页 > 图灵资讯 > 行业资讯> Python yield实现迭代器协议

Python yield实现迭代器协议

发布时间:2024-06-29 21:46:34

说明

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

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

模块中的Iterator抽象基类可用于检查collections。

实例

>>>deffunc():
...yield'Iam'
...yield'agenerator!'
...
>>>type(func)#Afunctionwithyieldisstillafunction
<type'function'>
>>>gen=func()
>>>type(gen)#butitreturnsagenerator
<type'generator'>
>>>hasattr(gen,'__iter__')#that'saniterable
True
>>>hasattr(gen,'next')#andwith.next(.__next__inpython3
True

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

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

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09