首页 > 解决方案 > 如何在可等待的子类中使用 super()?

问题描述

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

让我们从一个非常简单的基类开始,它创建在短暂睡眠后异步返回 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())

标签: pythonpython-asyncio

解决方案


await 方法必须返回一个迭代器,因此您可以将其设为生成器并使用yield from语法:

class R100(R99):

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

推荐阅读