如何正确继承class方法

How to properly inherit class method

我有一个创建连接池的数据库连接 class。现在,随着应用程序的增长,我正在添加不同类型的数据库编写器,我想将数据库连接移动到一个单独的 class 并从中继承。到目前为止我有这个:

class ServiceDB:
    @classmethod
    async def init(cls, settings):
        self = ServiceDB()
        self.pool = await asyncpg.create_pool(
            database=settings["POSTGRES_DB"],
            user=settings["POSTGRES_USER"],
            password=settings["POSTGRES_PASSWORD"],
            host=settings["DB_HOST"],
            port=settings["DB_PORT"],
        )
        return self



class ChildWriter(ServiceDB):
    async def write_db(self, query):
        # Write to specific table
        pass



if __name__ == "__main__":
    settings = {'info': "some connection settings"}
    query = "SELECT * FROM 'table'"
    connection = await ChildWriter().init(settings)
    await connection.write_db(msg, query)

当我 运行 这个我得到 AttributeError: 'ServiceDB' object has no attribute 'write_db'。如何使用 write_db 方法正确扩展 ServiceDB

类方法接收“current class”作为第一个参数。实例化此 cls,而不是固定基数 class.

class ServiceDB:
    @classmethod
    async def init(cls, settings):
        self = cls()  # cls is the *current* class, not just ServiceDB
        self.pool = await asyncpg.create_pool(
            database=settings["POSTGRES_DB"],
            user=settings["POSTGRES_USER"],
            password=settings["POSTGRES_PASSWORD"],
            host=settings["DB_HOST"],
            port=settings["DB_PORT"],
        )
        return self

请注意,理想情况下,所有属性都通过 __init__ 而不是单独的 classmethod 构造函数设置。单独的构造函数应该只传递外部构造的任何属性。

class ServiceDB:
    def __init__(self, pool):
        self.pool = pool

    @classmethod
    async def init(cls, settings, **kwargs):
        pool = await asyncpg.create_pool(
            database=settings["POSTGRES_DB"],
            user=settings["POSTGRES_USER"],
            password=settings["POSTGRES_PASSWORD"],
            host=settings["DB_HOST"],
            port=settings["DB_PORT"],
        )
        return cls(pool=pool, **kwargs)

class ChildWriter(ServiceDB):
    async def write_db(self, query): ...

if __name__ == "__main__":
    settings = {'info': "some connection settings"}
    query = "SELECT * FROM 'table'"
    # call classmethod on class   V
    connection = await ChildWriter.init(settings)
    await connection.write_db(msg, query)