VPf*_*PfB 7 python python-asyncio
我想通过子类化为现有的等待类添加一个新功能.
让我们从一个非常简单的基类开始,创建在短暂睡眠后异步返回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())
Run Code Online (Sandbox Code Playgroud)
该await方法必须返回一个迭代器,所以你可以把它一台发电机,并使用从产量语法:
class R100(R99):
def __await__(self):
v = yield from super().__await__()
return v + 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
411 次 |
| 最近记录: |