IoC Container sample code of python
LooseCoupling Requirement
main文件中,调用底层同功能模块,
一般写法是在 main中,显示引用底层模块。
这构成了 下层对象 直接出现在上层代码中, 上层代码改变,需要考虑是否影响底层代码。
按照依赖倒置原则,需要定义中间抽象层,上层只依赖抽象层, 对底层,上层统一管理,需要时候调用。
IoC Container Demo
https://github.com/fanqingsong/code_snippet/tree/master/python/IoCContainer
main.py -- 负责上层逻辑
service
hello.py -- 业务
world.py -- 业务
main.py
''' https://stackoverflow.com/questions/42401495/how-to-dynamically-import-modules ''' import importlib import os this_file_path = os.path.abspath(__file__) this_file_dir = os.path.dirname(this_file_path) service_path = os.path.join(this_file_dir, "service") service_files = os.listdir(service_path) services = {} for one_file in service_files: print(one_file) file_name = os.path.basename(one_file) print(file_name) module_name = file_name.replace(".py", "") print(module_name) module_path = ".".join(["python", "IoCContainer", "service", module_name]) print(module_path) print(os.path.splitext(file_name)) suffix = os.path.splitext(file_name)[-1] if suffix == ".py": print("adding-----------------") one_module = importlib.import_module(module_path) one_service_class = getattr(one_module, "Service") services[module_name] = one_service_class() print("=======================") services['hello'].run()
hello.py
class Service(): def run(self): print('hello service')
world.py
class Service(): def run(self): print('world service')
参考
模块文件动态加载
https://stackoverflow.com/questions/42401495/how-to-dynamically-import-modules
https://www.tutorialspoint.com/How-I-can-dynamically-import-Python-module
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。