在子包中动态导入模块

1 投票
1 回答
1199 浏览
提问于 2025-04-17 21:08

我正在尝试导入一个叫做 uberModule 的模块,并想获取里面的 "test" 类,但是使用 getattr 时找不到它,为什么呢?谢谢。

AttributeError: 'module' object has no attribute 'test'

这是我的代码,main.py:

from importlib import import_module
module = import_module("modules.uberModule")
cls = getattr(module, 'test')

uberModule.py :

class test():
    def __init__(self):
       print "such wow"

目录结构:

.
├── modules
│   ├── __init__.py
│   └── uberModule
│       ├── __init__.py
│       └── uberModule.py
├── __init__.py
├── main.py

1 个回答

0

那应该是:

module = import_module("modules.uberModule.uberModule")

除非 uberModule/__init__.py 导入了 uberModule 的内容(我想应该没有)

撰写回答