yield方法引入,

这里存在的问题是,如果你想创建从0到1,000,000这样一个很大的序列,你不得不创建能容纳1,000,000个整数的列表。

但是当加入了生成器之后,你可以不用创建完整的序列,你只需要能够每次保存一个整数的内存即可。

import asyncio

@asyncio.coroutine
def countdown(number, n):
    while n > 0:
        yield from asyncio.sleep(1)
        print("T-minus", n, "({})".format(number))
        n -= 1
        if n == 10 and number=="A":
            raise ValueError

loop = asyncio.get_event_loop()

tasks = [
    asyncio.ensure_future(countdown("A", 20)),
    asyncio.ensure_future(countdown("B", 33)),
]
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

 

 

看代码

import asyncio

@asyncio.coroutine
def countdown(number, n):
    while n > 0:
        yield from asyncio.sleep(1)
        print("T-minus", n, "({})".format(number))
        n -= 1
        if n == 10 and number=="A":
            raise ValueError

loop = asyncio.get_event_loop()

tasks = [
    asyncio.ensure_future(countdown("A", 20)),
    asyncio.ensure_future(countdown("B", 33)),
]
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

 

原理讲的特别好

http://python.jobbole.com/86481/

相关文章:

  • 2021-08-04
  • 2021-10-06
  • 2022-01-04
  • 2021-09-04
  • 2021-11-04
  • 1970-01-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-11
  • 2021-12-02
  • 2021-11-22
  • 2022-02-01
  • 2022-12-23
  • 2021-11-09
相关资源
相似解决方案