【问题标题】:How do I use async to loop over a list and call a list object's own function如何使用异步循环遍历列表并调用列表对象自己的函数
【发布时间】:2020-03-02 23:21:27
【问题描述】:

如何循环遍历对象列表并调用它们的函数。例如:

class Cat:
    def talk():
        print("Meow")

class Dog:
    def talk():
        print("Woof")


cat = Cat()
dog = Dog()

animal_list = [cat, dog]

# How would I do these async?
for animal in animal_list:
    animal.talk()

此线程 How to use an async for loop to iterate over a list? 建议使用 asyncio,但没有举例说明如何让对象调用它自己的函数,例如 animal.talk()

【问题讨论】:

  • 您可以将talk 函数设为异步函数吗?这样更容易。
  • 是的,看起来怎么样?
  • 您能更详细地描述您想要实现的目标吗?具体来说,当前代码有什么问题,以及您希望新代码的行为方式。请注意,链接的问题不只是根据用例“推荐”使用 asyncio,而是从 async for 开始。除非您了解 async for 的作用(提示:它不会自动并行化您的循环,几乎可以说它的作用相反 - 请参阅 herehere),否则使用它没有任何意义。

标签: python asynchronous python-asyncio


【解决方案1】:

使谈话功能异步,否则使用asyncio 毫无意义。

class Cat:
    async def talk():
        print("Meow")

class Dog:
    async def talk():
        print("Woof")


cat = Cat()
dog = Dog()

animal_list = [cat, dog]

创建由animal.talk() 返回的协程列表(可迭代)。

coroutines = map(lambda animal : animal.talk(), animal_list)coroutines = [animal.talk() for animal in animal_list] 可以。

然后最终调度执行的协程列表。

# This returns the results of the async functions together.
results = await asyncio.gather(coroutines)

# This returns the results one by one.
for future in asyncio.as_completed(coroutines):
    result = await future

cat.talk()dog.talk() 将异步执行,这意味着它们的执行顺序没有保证,可能会在不同的线程上运行。但是这里的talk 函数非常简单,以至于它看起来像是同步运行的,并没有带来任何真正的好处。

但如果talk 涉及发出网络请求或长时间、繁重的计算,并且animal_list 非常长,那么这样做有助于提高性能。

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2010-10-22
    • 2012-05-30
    • 2013-05-29
    • 1970-01-01
    相关资源
    最近更新 更多