模块的依赖注入

发布于 2024-11-17 04:05:09 字数 160 浏览 5 评论 0原文

考虑一个模块,例如some_module,不同的模块在同一解释器进程中使用。该模块将具有单一上下文。为了使 some_module 方法正常工作,它必须接收类实例的依赖注入。

将依赖项注入到模块中的 Pythonic 且优雅的方法是什么?

Consider a module, e.g. some_module, that various modules use in the same interpreter process. This module would have a single context. In order for some_module methods to work, it must receive a dependency injection of a class instance.

What would be a pythonic and elegant way to inject the dependency to the module?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

青春有你 2024-11-24 04:05:09

使用全局模块。

import some_module
some_module.classinstance = MyClass()

如果没有收到,some_module 可以使用代码来设置默认实例,或者只需将 classinstance 设置为 None 并检查以确保已设置当方法被调用时。

Use a module global.

import some_module
some_module.classinstance = MyClass()

some_module can have code to set up a default instance if one is not received, or just set classinstance to None and check to make sure it's set when the methods are invoked.

凡间太子 2024-11-24 04:05:09

恕我直言,成熟的依赖注入和所有术语更适合像Java这样的静态类型语言,在Python中你可以很容易地实现这一点,例如这里是一个简单的注入

class DefaultLogger(object):
   def log(self, line):
      print line

_features = {
   'logger': DefaultLogger
   }

def set_feature(name, feature):
   _features[name] = feature

def get_feature(name):
   return _features[name]()

class Whatever(object):

   def dosomething(self):
      feature = get_feature('logger')

      for i in range(5):
         feature.log("task %s"%i)

if __name__ == "__main__":
   class MyLogger(object):
      def log(sef, line):
         print "Cool",line

   set_feature('logger', MyLogger)

   Whatever().dosomething()

输出:

Cool task 0
Cool task 1
Cool task 2
Cool task 3
Cool task 4

如果您认为缺少某些内容,我们可以轻松添加它,即 python。

IMHo opinion full fledged Dependency Injection with all jargon is better suited to statically typed languages like Java, in python you can accomplish that very easily e.g here is a bare bone injection

class DefaultLogger(object):
   def log(self, line):
      print line

_features = {
   'logger': DefaultLogger
   }

def set_feature(name, feature):
   _features[name] = feature

def get_feature(name):
   return _features[name]()

class Whatever(object):

   def dosomething(self):
      feature = get_feature('logger')

      for i in range(5):
         feature.log("task %s"%i)

if __name__ == "__main__":
   class MyLogger(object):
      def log(sef, line):
         print "Cool",line

   set_feature('logger', MyLogger)

   Whatever().dosomething()

output:

Cool task 0
Cool task 1
Cool task 2
Cool task 3
Cool task 4

If you think something is missing we can add that easily, its python.

呆橘 2024-11-24 04:05:09

您可以使用 dependencies来实现您的目标。

You can use the dependencies package to achieve your goal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文