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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章