栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 生成器

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 生成器

生成器函数:
1. 里面有yield
2. 生成器函数在执行的时候,实际上是创建一个生成器出来
3. 必须使用__next__()来执行一段代码,会自动地执行到下一个yield结束
4. yield也是返回的意思,可以让一个函数分段执行
5. 当后面没有yield之后,再次__next__()会报错 StopIteration
6. 还可以适用send(),往yield结束的位置向函数传值

生成器代码:

def robor_produce():
     for i in range(10):
          yield  i

tmp = robor_produce()
while True:
     try:
          print(tmp.__next__())
     except StopIteration:
          break

打印结果:

0
1
2
3
4
5
6
7
8
9

加入 send() 往函数里传入参数,但是必须要先用__next__()

def robor_produce():
     print("step 1")
     #b 接收send回来的数据
     a = yield "step 2"
     print("a = ", a)
     #c 接受send回来的数据
     b = yield "step3"
     print("b = ", b)
     yield 'end'

tmp = robor_produce()
#必须先用__next__()
print(tmp.__next__())
while True:
     try:
          print(tmp.send("111"))
     except StopIteration:
          break

打印结果:

step 1
step 2
a =  111
step3
b =  111
end
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/308022.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号