yield實現斐波那契序列: Send: send函數用來向fib_iter發送數據,這樣數據就可以雙向流動。我們嘗試使用send來模擬一個比較慢的生成器,我們讓它一秒鐘生成一個數: yield from 是什麼? 在上面的yield中,我們通過for迴圈使用__next__()方法來獲取下一個值, ...
yield實現斐波那契序列:
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來模擬一個比較慢的生成器,我們讓它一秒鐘生成一個數:
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 它可以簡化這個過程,看看實例:
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)))
執行結果:
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傳遞信息:
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:
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