yield的__next__()和send()的用法,詳見代碼spa
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)