yield方法引入,
这里存在的问题是,如果你想创建从0到1,000,000这样一个很大的序列,你不得不创建能容纳1,000,000个整数的列表。
但是当加入了生成器之后,你可以不用创建完整的序列,你只需要能够每次保存一个整数的内存即可。
import asyncio @asyncio.coroutine
def countdown(number, n):
while n > :
yield from asyncio.sleep()
print("T-minus", n, "({})".format(number))
n -=
if n == and number=="A":
raise ValueError loop = asyncio.get_event_loop() tasks = [
asyncio.ensure_future(countdown("A", )),
asyncio.ensure_future(countdown("B", )),
]
loop.run_until_complete(asyncio.wait(tasks)) loop.close()
看代码
import asyncio @asyncio.coroutine
def countdown(number, n):
while n > :
yield from asyncio.sleep()
print("T-minus", n, "({})".format(number))
n -=
if n == and number=="A":
raise ValueError loop = asyncio.get_event_loop() tasks = [
asyncio.ensure_future(countdown("A", )),
asyncio.ensure_future(countdown("B", )),
]
loop.run_until_complete(asyncio.wait(tasks)) loop.close()
原理讲的特别好
http://python.jobbole.com/86481/