Bjö*_*lex 5 python abstract-class python-asyncio
我如何要求抽象基类将特定方法实现为协程。例如,考虑这个 ABC:
import abc
class Foo(abc.ABC):
@abc.abstractmethod
async def func():
pass
Run Code Online (Sandbox Code Playgroud)
现在,当我子类化并实例化它时:
class Bar(Foo):
def func():
pass
b = Bar()
Run Code Online (Sandbox Code Playgroud)
这成功了,尽管func不是async,就像在 ABC 中一样。我该怎么做才能使这仅在func是时成功async?
您可以使用__new__并检查子类是否以及如何覆盖父类的 coros。
import asyncio
import abc
import inspect
class A:
def __new__(cls, *arg, **kwargs):
# get all coros of A
parent_coros = inspect.getmembers(A, predicate=inspect.iscoroutinefunction)
# check if parent's coros are still coros in a child
for coro in parent_coros:
child_method = getattr(cls, coro[0])
if not inspect.iscoroutinefunction(child_method):
raise RuntimeError('The method %s must be a coroutine' % (child_method,))
return super(A, cls).__new__(cls, *arg, **kwargs)
@abc.abstractmethod
async def my_func(self):
pass
class B(A):
async def my_func(self):
await asyncio.sleep(1)
print('bb')
class C(A):
def my_func(self):
print('cc')
async def main():
b = B()
await b.my_func()
c = C() # this will trigger the RuntimeError
await c.my_func()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)
__new__以抑制此约束不仅async可以等待。例如
async def _change_in_db(self, key, value):
# some db logic
pass
def change(self, key, value):
if self.is_validate(value):
raise Exception('Value is not valid')
return self._change_in_db(key, value)
Run Code Online (Sandbox Code Playgroud)
可以change这样打电话
await o.change(key, value)
Run Code Online (Sandbox Code Playgroud)
更不用说__await__在对象、其他原始期货、任务中......