简体   繁体   English

Python策略模式:动态导入类文件

[英]Python Strategy pattern: Dynamically import class files

I am trying to build a software package that fixes arbitrary data inconsistencies in one of my databases. 我正在尝试构建一个软件包,该软件包可以解决我的一个数据库中的任意数据不一致问题。 My design includes two classes - Problem and Fix . 我的设计包括两个类ProblemFix

The problems are SQL queries stored as .cfg files (eg problem_001.cfg ), and the fixers are stored as Python files (eg fix_001.py ). 问题是将SQL查询存储为.cfg文件(例如problem_001.cfg ),而fix_001.py也存储为Python文件(例如fix_001.py )。 The query config file has a reference to the Python file name. 查询配置文件具有对Python文件名的引用。 Each fixer has a single class Fix , which inherits from a base class BaseFix . 每个Fix都有一个单独的Fix类,它从基类BaseFix继承。

`-- problems
    |-- problem_100.cfg
    |-- problem_200.cfg
    |-- problem_300.cfg
    `-- ...
`-- fixer
    |-- __init__.py
    |   |-- fixers
    |   |   |-- fix_100.py
    |   |   |-- fix_200.py
    |   |   |-- fix_300.py
    |   |   |-- ...
    |   `-- ...
    `-- ...

I would like to instantiate Problem files and supply them with Fix objects in a clean way. 我想实例化Problem文件,并以干净的方式为它们提供Fix对象。 Is there a way to do it without keepping all the fixers in the same file? 有没有一种方法可以将所有修复程序都保留在同一文件中?

UPDATE: 更新:

This is the final code that worked (thanks, @Space_C0wb0y): 这是有效的最终代码(感谢@ Space_C0wb0y):

    fixer_name='fix_100'
    self.fixer=__import__('fixer.fixers', globals(), locals(), 
                 [fixer_name]).__dict__[fixer_name].Fix() 

You can dynamically import modules using the builtin __import__ , which takes the module-name as string-argument (see here ). 您可以使用内置的__import__来动态导入模块,该模块将模块名作为字符串参数(请参见此处 )。 The modules do have to be in the module search path . 模块必须位于模块搜索路径中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM