首页 > 解决方案 > 如何动态导入和实例化类?

问题描述

我有一个需要一些复杂信息验证的应用程序。随着团队随着复杂性的增长,验证(以 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'

标签: pythonpython-3.xoopattributeerror

解决方案


推荐阅读