码迷,mamicode.com
首页 > 编程语言 > 详细

PYTHON学习0038:函数---生成器send方法---2019-7-2

时间:2019-07-02 13:30:08      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:yield   some   next   return   ==   python   none   通过   例子   

函数生成器中,send的作用:
1、换新生成器继续执行
2、发送一个信息到生成器内部。
和next()的区别:
next只是唤醒生成器并继续执行,next()就相当于没有发送值或者默认发送一个None给函数内部。
send(None)和next()效果一样。
例子:
def range(n):
count=0
while count<n:
print("count",count)
count+=1
sign=yield count
print("------sign",sign)
t=range(3)
next(t)
print("i will go to do somethingeles")
t.send("stop")
输出为:
count 0
i will go to do somethingeles
------sign stop
count 1

说明t.send("stop")把括号里的“stop”传到函数里的sign了。
所以可以通过判断传给sign的值来决定要不要终止函数内的循环:
def range(n):
count=0
while count<n:
print("count",count)
count+=1
sign=yield count
if sign=="stop":
break(或者return也一样)
print("------sign",sign)
t=range(3)
next(t)
print("i will go to do somethingeles")
t.send("stop")

send

PYTHON学习0038:函数---生成器send方法---2019-7-2

标签:yield   some   next   return   ==   python   none   通过   例子   

原文地址:https://blog.51cto.com/13543767/2416147

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!