yield實現斐波那契序列:python
import sys, time def fib(): a,b,c = 0,1,0 while True: yield c a,b = b, c c = a + b if __name__ == '__main__': fib_iter = fib() for i in range(int(sys.argv[1])): print(fib_iter.__next__())
Send:異步
send函數用來向fib_iter發送數據,這樣數據就能夠雙向流動。咱們嘗試使用send來模擬一個比較慢的生成器,咱們讓它一秒鐘生成一個數:async
import sys, time def fib(): a,b,c = 0,1,0 while True: sleep_sec = yield c time.sleep(sleep_sec) a,b = b, c c = a + b def fib1(): index = 1 a = 0 b = 1 while index: yield b a, b = b, a + b index += 1 if __name__ == '__main__': fib_iter = fib() print(fib_iter.__next__()) #先執行一下,讓它停留在yield for i in range(int(sys.argv[1])): result = fib_iter.send(1) # print(result)
yield from 是什麼?函數
在上面的yield中,咱們經過for循環使用__next__()方法來獲取下一個值,也就是說想要獲取下一個值就要從新yield一下;yield from 它能夠簡化這個過程,看看實例:oop
import sys, time def fib(n): a,b,c = 0,1,0 while c < n: yield c a,b = b, c c = a + b def gener(n): yield from fib(n) if __name__ == '__main__': print(list(gener(5000)))
執行結果:spa
D:\>python fib.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4
181]
yield from , send傳遞信息:code
import sys, time def fib(n): a,b,c = 0,1,0 while c < n: sleep_sec = yield c time.sleep(sleep_sec) a,b = b, c c = a + b def gener(n): yield from fib(n) if __name__ == '__main__': gen = gener(10) print(gen.send(None)) print(gen.send(1)) print(gen.send(1))
執行結果:協程
D:\>python fib.py
0
1
1
asyncio 和 yield from:blog
asyncio是一個基於事件循環的實現異步的I/O模塊。經過yield from, 咱們能夠將協程asynico.sleep的控制權交給事件循環,而後掛起當前協程;以後,由事件循環決定什麼時候喚醒asyncio.sleep,而後接着執行後面的代碼; 實例中咱們用sleep來模擬阻塞:事件
import sys, time, asyncio def fib(n): a,b,c = 0,1,0 while c < n: yield from asyncio.sleep(2) print('-->', c) a,b = b, c c = a + b def stupid_fib(n): a,b,c = 0,1,0 while c < n: yield from asyncio.sleep(2) print('==>', c) a,b = b,c c = a + b if __name__ == '__main__': loop = asyncio.get_event_loop() tasks = [asyncio.async(fib(10)), asyncio.async(stupid_fib(10))] loop.run_until_complete(asyncio.wait(tasks)) print('all task finished') loop.close()
執行結果:
D:\>python fib.py --> 0 ==> 0 --> 1 ==> 1 --> 1 ==> 1 --> 2 ==> 2 --> 3 ==> 3