def gen():python
value=0函數
while True:spa
receive = yield valuecode
if receive=='e':協程
breakci
value = 'got: %s' % receivestring
g=gen()it
print(g.send(None)) io
print(g.send('aaa'))ast
print(g.send(3))
print(g.send('e'))
執行流程:
0
got: aaa
got: 3
Traceback (most recent call last):
File "C:\string.bak.py", line 20, in <module>
print(g.send('e'))
StopIteration
yield表達式實現協程
def consumer(): r = 'yield' while True: #當下邊語句執行時,先執行yield r,而後consumer暫停,此時賦值運算還未進行 #等到producer調用send()時,send()的參數做爲yield r表達式的值賦給等號左邊 n = yield r #yield表達式能夠接收send()發出的參數 if not n: return print('[CONSUMER] Consuming %s...' % n) r = '200 OK' def produce(c): c.send(None) #send須要先調用send(None),由於只有生成器是暫停狀態才能夠接收send的參數 n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) #調用consumer生成器 print('[PRODUCER] Consumer return: %s' % r) c.close() c = consumer() produce(c)
def gen(): a = yield 1 print('yield a % s' % a) b = yield 2 print('yield b % s' % b) c = yield 3 print('yield c % s' % c) r = gen() x = next(r) print('next x %s' % x) y = r.send(10) print('next y %s' %y) z = next(r) print('next z %s' % z)
能夠看到實際上y=r.send(10)
的參數10是賦給了a。整個運行過程即執行x=next(r)
以後,gen()執行了yield 1
而後暫停,沒有進行對a的賦值。但再調用y=r.send(10)
時賦值過程繼續,並把10賦給了a.