类内使用importlib时出现ModuleNotFoundError
我正在尝试使用 importlib.import_module
导入一个对象,但无论我怎么尝试,都出现 ModuleNotFoundError
的错误。我已经阅读了很多相关的帖子,但还是没能解决我的问题。
非常感谢任何能够提供帮助的人!
我的项目文件夹结构如下:
root/
checks.py
database.py
main.py
在 checks.py
文件中,我定义了 Check
类。里面包含了以下代码。
class Check():
def __init__(self, action):
self.action = action
def speak(self):
print(self.action)
class CheckOne(Check):
def __init__(self):
Check.__init__(self, "Performing the first check.")
def apply_(self):
self.speak()
在 database.py
文件中,我定义了 Database
类。里面包含了以下代码。
class Database():
def __init__(self):
# The checks we want to perform
self.check_names = ['CheckOne']
def apply_checks(self):
import importlib
checks = [importlib.import_module(f'checks.{i}') for i in self.check_names]
for c in checks:
c().apply_()
在 main.py
文件中,我创建了一个 Database
对象,并调用了 apply_checks
方法。里面包含了以下代码:
from database import Database
db = Database()
db.apply_checks()
当我运行 main.py
时,出现了以下错误:
ModuleNotFoundError: No module named 'checks.CheckOne'; 'checks' is not a package
我想要的是 Database.apply_checks
方法能够将 CheckOne
类导入到一个列表中,实例化它,然后执行 CheckOne.apply_
方法(打印 "Performing the first check."
)。
我尝试在 Database
类定义中放入 import checks
和 from . import checks
,但都没有成功。我还尝试在 root
下添加一个 __init__.py
文件。
感谢你的阅读,我很感激你的反馈!
1 个回答
1
试试这个:
import checks
class Database():
def __init__(self):
# The checks we want to perform
self.check_names = ['CheckOne']
def apply_checks(self):
check_classes = [getattr(checks, name) for name in self.check_names]
for cls in check_classes:
cls().apply_()