python的yield与send实例详解

首先看两段代码及其输出

def gener(num):
    while True:
        print("0:before yield num is: %d" % num) 
        num = yield 
        print("1:after yield num  is %d" % num) 
    print("exc end")

g = gener(1)
g.send(None)
print("goto loop")
for i in range(5):
    print("---loop---")
    print(">>>>send back:" + str(g.send(i)))


# 输出为 >>
0:before yield num is: 1
goto loop
---loop---
1:after yield num  is 0
0:before yield num is: 0
>>>>send back:None
---loop---
1:after yield num  is 1
0:before yield num is: 1
>>>>send back:None

def gener(num):
    while True:
        print("0:before yield num is: %d" % num) 
        num = yield num**2 # 代码唯一有变化的地方
        print("1:after yield num  is %d" % num) 
    print("exc end")

g = gener(1)
g.send(None)
print("goto loop")
for i in range(5):
    print("---loop---")
    print(">>>>send back:" + str(g.send(i)))


# 输出为 >>
0:before yield num is: 1
goto loop
---loop---
1:after yield num  is 0
0:before yield num is: 0
>>>>send back:0
---loop---
1:after yield num  is 1
0:before yield num is: 1
>>>>send back:1

分析

generator函数调用后,第一次send(None),generator执行到yield之前,之后每次调用send(), 从yield所在行开始执行,运行到片段结尾或再次遇到yield, generator从yield中接受参数,如果yield后有表达式,则返回表达式的值,类似return关键字的功能。yield关键字保存了generator每次的执行状态。

你可能感兴趣的:(python的yield与send实例详解)