yield的__next__()和send()的用法,详见代码
1 def D(): 2 n = 1 3 while n < 5: 4 m = yield n 5 print("m:",m) 6 print("n:",n) 7 n += 4 8 yield 10 9 yield 10 11 d = D() 12 # __next__() 是寻找下一个yield,并将yield后面的值返回,右面没值,则返回None,如果没找到yield 就报错,__next__()不给yield传值 13 # j = d.__next__() 14 # print(j) 15 # j = d.__next__() 16 # print(j) 17 18 # send(x)是返回上一个中断的yield,并将值传给yield,然后寻找下一个yield,并将yield后面的值返回,如果没找到下一个yield,就报错 19 # 如果在这之前没有开启generator,则只能传递None值给yield (使用 send(None)),并立即返回yield后面的值 20 # j = d.send(3) # TypeError: can't send non-None value to a just-started generator 21 22 def exam1(): 23 j = d.send(None) # j = 1 , 返回的是第一次遇到yield后 n的值 24 print(j) # j = 1 25 # 26 # 1 27 j = d.send(3) 28 print(j) 29 # 1 30 # m: 3 31 # n: 1 32 # 10 33 j = d.__next__() 34 print(j) 35 # 1 36 # m: 3 37 # n: 1 38 # 10 39 # 4 40 j = d.send(20)