【发布时间】:2019-09-05 20:11:18
【问题描述】:
我正在编写一个类,并想在__init__ 方法中使用异步函数来设置该类所需的一些变量。问题是,我不能这样做,因为__init__ 必须是同步的。
这是我的代码的相关部分(为简单起见进行了编辑,逻辑保持不变):
# This has to be called outside of the class
asyncDatabaseConnection = startDBConnection()
class discordBot(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Init is only run once, but we cant use async stuff here
self.firstRun = True
async def on_ready(self):
# Other stuff happens here but it doesen't involve this question
# on_ready is called when bot is ready, but can be called multiple times when running
# (if bot has to reconnect to API), so we have to check
if self.firstRun:
await asyncDatabaseConnection.setValue("key", "value")
self.firstRun = False
if __name__ == "__main__":
# Instance class and start async stuff
bot = discordBot()
bot.run()
如您所见,它适用于 Discord 机器人,但这并不重要,更多的是关于逻辑。
我要调用的函数是asyncDatabaseConnection.setValue("key", "value")。
就像我说的,我不能从__init__ 调用它,因为__init__ 必须是同步的,所以我在init 调用期间将firstRun 设置为True,然后我可以稍后用它来告诉代码之前是否运行过
on_ready 是一个在机器人准备好开始发送/接收数据时调用的函数,因此我可以将其用作第二个 __init__。问题在于on_ready可以在程序运行过程中多次调用,这意味着我必须有我之前描述的firstRun检查。
这似乎有很多代码只是为了在启动时做一件事(以及在调用on_ready 时增加开销,无论多么小)。有没有更清洁的方法?
【问题讨论】:
-
我认为你应该有一个函数来执行异步任务,然后同步初始化并返回类的实例。
标签: python async-await discord.py