python - 如何动态导入和实例化类?
问题描述
我有一个需要一些复杂信息验证的应用程序。随着团队随着复杂性的增长,验证(以 Python 类的形式)将不断添加和调整。因此,我试图想出一种干净的方法,最终只是动态地处理来自主validator.py
文件的所有验证 Python 类。
到目前为止,我的尝试产生了不错的AttributeError
.
也就是说,我的项目结构是:
validator
validators
census_data.py
ethnicity.py
financials.py
__init__.py
validator.py
在我的validator.py
文件中,我有以下代码:
class Validator:
validators = ['validator.validators.financials']
def run(self):
for validator in self.validators:
module = __import__(validator)
# Haven't implemented the dynamic split of the class name yet
validator_class = getattr(module, 'Financials')
validator_class.run()
在financials.py
文件中,我有以下内容:
class Financials:
def run(self):
return True
当我通过测试触发validator.py
文件时,出现以下错误:
AttributeError module 'validator' has no attribute 'Financials'
解决方案
推荐阅读
- android - Android Studio Emulator getExternalFilesDir() 在设备文件资源管理器中“权限被拒绝”
- amazon-s3 - 使用 django s3 sqlite 包来使用 sqlite db
- java - Kafka 流消耗为 CSV
- parameters - Magento \\OfflineShipping\\Model\\SalesRule\\Calculator Magento 2 的 $rulesApplier 参数提供的参数配置无效
- python - 字典中存在键时出现KeyError
- vba - 交叉表查询访问
- javascript - 如何在 Javascript 中通过 datepicker 过滤 JSON 数据?
- opencl - 英特尔 OpenCL 是否有任何 C++ 支持?
- python - PyQt5 中的多线程应用程序中的分段错误(错误)
- python - 将python中的类对象与指定条件进行比较