gpt4 book ai didi

python - 如何在可等待的子类中使用 super()?

转载 作者:太空狗 更新时间:2023-10-29 21:44:58 25 4
gpt4 key购买 nike

我想通过子类化现有的可等待类来为其添加新功能。

让我们从一个非常简单的基类开始创建对象,这些对象在短暂休眠后异步返回 99。子类应该只向结果添加 +1。

我找不到使用 super() 来引用基类的正确方法。

import asyncio

class R99:
def __await__(self):
loop = asyncio.get_event_loop()
fut = loop.create_future()
loop.call_later(0.5, fut.set_result, 99)
return fut.__await__()

class R100(R99):
async def add1(self):
v = await R99()
#v = await super().__await__() # <== error
return v + 1

def __await__(self):
return self.add1().__await__()

async def test():
print(await R99())
print(await R100())

asyncio.get_event_loop().run_until_complete(test())

最佳答案

await method必须返回一个迭代器,所以你可以使它成为一个生成器并使用 yield from语法:

class R100(R99):

def __await__(self):
v = yield from super().__await__()
return v + 1

关于python - 如何在可等待的子类中使用 super()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52605760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com