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

函数生成器中,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

猜你喜欢

转载自blog.51cto.com/13543767/2416147