我正在编写一个类,并希望在
以下是我代码的相关部分(为简化起见进行了编辑,逻辑保持不变):
__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__
必须是同步的,所以我将firstRun
设置为True
,并在init调用期间使用它,然后稍后可以使用它来告诉代码先前是否已运行
on_ready
是一个函数,当机器人准备好开始发送/接收数据时调用,因此我可以将其用作第二个__init__
。问题在于,on_ready
可以在程序运行期间多次调用,这意味着我必须具有我之前描述过的firstRun
检查。
这似乎是为了在启动时执行1件事(以及在调用on_ready
时添加开销,即使很小)。有没有更简洁的方法来做到这一点?