python - 如何使用异步遍历列表并调用列表对象自己的函数

标签 python asynchronous python-asyncio

我如何遍历异步对象列表并调用它们的函数。例如:

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()

最佳答案

使对话功能异步,否则使用 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 非常长,那么这样做可以帮助提高性能。

关于python - 如何使用异步遍历列表并调用列表对象自己的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60498008/

相关文章:

python - 获得整数数组汉明距离的最快方法

python - 改进了编码,节省了如何检查Python中是否有两条线段交叉

python - 具有 XPath 支持的快速 python XML 验证器

c# - 如何在不需要等待当前函数/线程的结果的情况下运行异步任务?

.net - Threading.Tasks Dispose 含义问题

python-3.x - 系统 :1: RuntimeWarning: coroutine was never awaited

python - 检查系列的 dtype 是否属于 pandas 中的 dtypes 列表

javascript - 我在异步函数中使用 Promise 是否正确?

python - 在事件循环中共享队列

python - 在 grpc python 中处理异步流请求