【发布时间】:2016-01-12 17:14:25
【问题描述】:
如何在构造函数或类主体中定义带有await 的类?
例如我想要的:
import asyncio
# some code
class Foo(object):
async def __init__(self, settings):
self.settings = settings
self.pool = await create_pool(dsn)
foo = Foo(settings)
# it raises:
# TypeError: __init__() should return None, not 'coroutine'
或带有类主体属性的示例:
class Foo(object):
self.pool = await create_pool(dsn) # Sure it raises syntax Error
def __init__(self, settings):
self.settings = settings
foo = Foo(settings)
我的解决方案(但我希望看到更优雅的方式)
class Foo(object):
def __init__(self, settings):
self.settings = settings
async def init(self):
self.pool = await create_pool(dsn)
foo = Foo(settings)
await foo.init()
【问题讨论】:
-
__new__可能会带来一些运气,尽管它可能并不优雅 -
我没有使用 3.5 的经验,而在其他语言中,由于 async/await 的病毒性质,这不起作用,但是您是否尝试过定义像
_pool_init(dsn)这样的异步函数,然后从__init__调用它?它将保留 init-in-constructor 的外观。 -
如果你使用古玩:curio.readthedocs.io/en/latest/…
-
使用
@classmethod????它是一个替代构造函数。把异步工作放在那里;然后在__init__中,只需设置self属性
标签: python python-3.x python-asyncio