异步 Python - 如何使类 __init__ 在类 __init__ 中运行异步函数

Epi*_*Boi 4 python init python-asyncio

假设我有这个:

class Test():
    def __init__(self, number):
        self.number = number
        await self.TestPrint()

    async def TestPrint(self):
        print(self.number)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这不起作用,因为__init__不是async,而且我无法调用await该函数。

我希望能够在假设我想维护这个函数 async 的情况TestPrint下运行。__init__

我还希望它与类之外的任何其他内容(其他函数、其他类、main 等)无关。

Blu*_*nix 5

就像切普纳在评论中提到的那样:

创建对象然后TestPrint在返回之前调用该方法的异步类方法听起来更合适。

这是最重要的首选方式,也是为什么有很多函数会初始化内部 asyncio 类,而不是直接实例化它们。

也就是说,如果您希望它接近类,您可以使用 a @classmethod,它可以是异步的。你的代码看起来像这样:

class Test():
    def __init__(self, number):
        self.number = number

    async def TestPrint(self):
            print(self.number)

    @classmethod
    async def with_print(cls, number):
        self = cls(number)
        await self.TestPrint()
        return self
Run Code Online (Sandbox Code Playgroud)
async def main():
    t = await Test.with_print(123)
    # 't' is now your Test instance.
    ...
Run Code Online (Sandbox Code Playgroud)