Python:在这种情况下如何重构和构建代码?

时间:2021-04-08 15:17:06

标签: python python-3.x python-asyncio

我非常坚持在这种情况下构建代码。有人能帮我解决这个问题吗?

|模块.py

import asyncio

class Server:
    def __init__(self):
        self.d = {}

    @classmethod
    async def create(cls):
        self = cls()
        await self.func()
        return self

    async def func(self):
        await asyncio.sleep(5)  # Some other async code here
        self.a = 12

    def reg(self, ev):
        def decorator(func):
            self.d[ev] = func()
            retun func
        return decorator

    def reg2(self, ev, func):
        self.d[ev] = func

|主文件

import asyncio
from module import Server

async def main():
    ser = await Server.create()
    # This would be another way... but i find the other way one neater
    serv.reg2('msg', some_handler)

# I want to decorate and register this using
# reg func; but since object is not created yet
# how do i acomplish this?
# @ser.reg('msg')
async def some_handler():
    ...

if __name__ == "__main__":
    asyncio.run(main())

我的目标的一些关键点:

  • 'some_handler' 函数除了注册时间外从不使用。也就是说,函数 soley 是为了注册而存在的,不会在其他任何地方使用。
  • 由于 Server 类需要异步初始化,因此无法全局完成。
  • (不知道这点有没有用)一般一个程序只创建一个Server实例。即使在其他模块中也不会有任何其他实例。

我如何建模我的代码以满足这个场景?我已经提到了注册函数的另一种方法,但我觉得我错过了一些东西,因为 some_handler 没有在其他任何地方使用。我曾考虑将 Server 类变成一个元类来注册和转换 main() 和 some_handler() 作为该类的一部分,但我正在寻求不同的观点和意见。

0 个答案:

没有答案
相关问题