我如何遍历异步对象列表并调用它们的函数。例如:
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/