RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1597289
Accepted
Handler
Handler
Asked:2024-10-20 21:08:23 +0000 UTC2024-10-20 21:08:23 +0000 UTC 2024-10-20 21:08:23 +0000 UTC

智能依赖注入

  • 772

我有一个小型库,我可以从网站获取一些数据,然后将其序列化。

我知道正确的开发方式是采用依赖注入的原理。在我的代码中有一个特定的基类,其中包含所有可用的方法。

class MyClass:
    def __init__(self):
        self.my_http_connection = HttpConnection()
    def my_method(self):
        return self.my_http_connection.get("address")

library = MyClass()

library.my_method()

在构造函数中,我创建了一个实例HttpConnection,事实上,我还有更多这样的实例,它们负责完全不同的情况。例如,哈希类。

以这种方式在构造函数中初始化类是否正确?这是好的做法吗?我阅读了 redis-py 和 aiogram 的源代码,这些东西是以完全不同的方式实现的。例如,aiogram 库中的任何方法都是通过__call__.有条件地

async def send_message(self):
    call = SendMessage()
    await self(call)

正因为如此,我不知道应该朝哪个方向去了解如何编写好的代码。

upd:我忘了提及我也分担课程的责任。我不会在一堂课上完成数学、http 请求和数据库工作。一个真实的例子如下所示:

class Explorer:
    def __init__(self, connection: Http):
        self.conn = connection

    def get(url):
        return self.conn.get(url)

class MyClass:
    def __init__(self):
        self.my_http_connection = Http()
        self.serializer = Serializer()
        self.explorer = Explorer(self.my_http_connection)
    def my_method(self):
        return self.serializer.serialize(self.explorer.get("address"))

library = MyClass()

library.my_method()

这就是我实现几乎所有代码的方式。而在explorer类中,以此类推,可能还有另一个类负责某事等等。

python
  • 1 1 个回答
  • 69 Views

1 个回答

  • Voted
  1. Best Answer
    Ben Puls
    2024-11-01T21:21:57Z2024-11-01T21:21:57Z

    其实按照你的例子使用是没有问题的。有些直接在构造函数中创建实例,而另一些(例如httpx库)则使用工厂方法:

    def _init_explorer(self, conn: Http) -> Explorer:
        return Explorer(conn)
    

    之后,类将看起来类似:

    class MyClass:
        def __init__(self):
            self.my_http_connection = Http()
            self.serializer = Serializer()
            self.explorer = self._init_explorer(self._my_connection)
    
        def _init_explorer(self, conn: Http) -> Explorer:
            return Explorer(conn)
    
        def my_method(self):
            return self.serializer.serialize(self.explorer.get("address"))
    

    没有任何限制;例如,在FastAPI中,所有内容都像您一样在构造函数中初始化。

    def __init__(self):
        # Конечно, в FastAPI конструктор выглядит иначе.
        # Это учебный пример
        self.router: routing.APIRouter = routing.APIRouter(
            routes=routes,
            redirect_slashes=redirect_slashes,
            dependency_overrides_provider=self,
            on_startup=on_startup,
            on_shutdown=on_shutdown,
            lifespan=lifespan,
            default_response_class=default_response_class,
            dependencies=dependencies,
            callbacks=callbacks,
            deprecated=deprecated,
            include_in_schema=include_in_schema,
            responses=responses,
            generate_unique_id_function=generate_unique_id_function,
        )
        ...
    
    • 1

相关问题

  • 是否可以以某种方式自定义 QTabWidget?

  • telebot.anihelper.ApiException 错误

  • Python。检查一个数字是否是 3 的幂。输出 无

  • 解析多个响应

  • 交换两个数组的元素,以便它们的新内容也反转

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5