Python策略模式:动态导入类文件
我正在尝试构建一个软件包来修复我的一个数据库中的任意数据不一致问题。我的设计包括两个类 - Problem
和 Fix
。
问题是存储为 .cfg
文件的 SQL 查询(例如 problem_001.cfg
),修复程序存储为 Python 文件(例如 fix_001.py
) >)。查询配置文件包含对 Python 文件名的引用。每个修复程序都有一个类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
| | |-- ...
| `-- ...
`-- ...
我想实例化 Problem
文件并以干净的方式为它们提供 Fix
对象。有没有办法在不将所有修复程序保存在同一个文件中的情况下完成此操作?
更新:
这是最终有效的代码(感谢@Space_C0wb0y):
fixer_name='fix_100'
self.fixer=__import__('fixer.fixers', globals(), locals(),
[fixer_name]).__dict__[fixer_name].Fix()
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
.
The problems are SQL queries stored as .cfg
files (e.g. problem_001.cfg
), and the fixers are stored as Python files (e.g. fix_001.py
). The query config file has a reference to the Python file name. Each fixer has a single class Fix
, which inherits from a base class 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. 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):
fixer_name='fix_100'
self.fixer=__import__('fixer.fixers', globals(), locals(),
[fixer_name]).__dict__[fixer_name].Fix()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用内置的
__import__
动态导入模块,它将模块名称作为字符串参数(请参阅 此处)。这些模块必须位于模块搜索路径 。You can dynamically import modules using the builtin
__import__
, which takes the module-name as string-argument (see here). The modules do have to be in the module search path.