Python - 动态类导入

5 投票
1 回答
1266 浏览
提问于 2025-04-17 05:58

我有一个这样的文件夹结构:

- MyProject
    - App1
        - some_module1.py
        - some_module2.py
    - App2
        - some_other_module1.py
        - some_other_module2.py

在每个模块里面(比如某个叫做 some_module1.py 的文件),都有一个类,这个类是从一个基础类继承而来的,在我的例子中,这个基础类叫做 Producer。

我想做的是动态加载这个类。为此,我有一个“已安装应用”的列表,长得像这样:

INSTALLED_APPS = (
    'App1',
    'App2',
)

我正在尝试写一个函数,去检查每个“应用”包里面是否有特定的生产者类,并确保这个类是从生产者基础类继承的。大概是这样的:

module_class = 'some_module1.SomeClass'

# Loop through each package in the INSTALLED_APPS tuple:
for app in INSTALL_APPS:
    try:
        #is the module_class found in this app?
        #App1.some_module1.SomeClass - Yes
        #App2.some_module1.SomeClass - No

        # is the class we found a subclass of Producer?
    exception ImportError:
        pass

我试过用 imp 和 importlib 来实验,但似乎这些方法不太适合这种导入方式。有没有什么办法可以实现这个呢?

1 个回答

5

你可能想看看:

  • __import__() 这个可以用来根据模块的名字(以字符串形式)导入模块;
  • dir() 可以用来获取一个模块里所有对象的名字(比如属性、函数等等);
  • inspect.isclass(getattr(<模块引用>, <对象名字>)) 可以用来识别模块中的类;
  • issubclass() 可以用来判断某个类是否是另一个类的子类,这里有详细解释

使用这些工具,你可以找到一个模块中所有继承自某个特定类的类。

我正在用这个方法动态创建模块中的类,这样它们的更新就能自动在更高层次上被考虑到。

撰写回答