如何使用依赖注入将对象注入模块?

0 投票
1 回答
609 浏览
提问于 2025-04-18 10:59

这是我的情况。我有一个包,里面包含了几个模块。它们都从 settings.py 文件中导入内容。不过,有些变量是依赖用户输入的。

...
# some CONSTANTS
...
PROJECT_DIR = Path(os.path.abspath(__file__)).parent.ancestor(1)
SCRIPT_DIR = PROJECT_DIR.child('scripts')
data_input = DATA_ROOT.child('input')
input_root = data_input.child(options.root_input) # the options object holds some user input

# then use input_root to get an instance of class Countries
from countries import Countries
country_object = Countries(input_root)

有几个模块需要使用 country_object。所以从 settings 中导入它们是最干净的解决方案。

我在了解 依赖注入 的概念,我觉得这在这里会很有用。但是我发现很难理解这个概念,所以我想知道如何使用依赖注入把选项对象注入到一个模块中?

1 个回答

1

谈到设计模式时,有两种思路:一种是让你的问题适应模式,另一种是让模式适应你的问题。我更倾向于后者。所以这是我对依赖注入模式在你问题上的调整:

class UserCountry(object):
     def __init__(self):be populated by user data
         self.Country = None

     def set_input_root(self, input_root):
         self.input_root = input_root # <-- this is a list/dict etc that I assume will 

     def __call__(self):
         if self.Country:
             return self.Country
         else:
             # Select country
             self.Country = Country
             return self.Country

settings.py文件中:

 user_country = UserCountries()

当定义input_root时:

settings.user_country.set_input_root(input_root) 

在其他模块中:

 settings.user_country() # gives you the Country object

撰写回答