Python模块识别异常:ModuleNotFoundError: No module named 'inherited'
问题解决:ModuleNotFoundError: No module named 'inherited'
核心原因
运行main.py时,Python的模块搜索路径(sys.path)默认包含main.py所在的父目录。inherited是modules目录下的子包,不在直接搜索路径里,所以直接写from inherited import classes会找不到模块。
两种修复方案
方案1:使用绝对导入
修改modules/sequences.py中的导入语句为:
from modules.inherited import classes
从顶层包modules开始指定完整路径,Python就能根据sys.path找到inherited子包。
方案2:使用相对导入
修改modules/sequences.py中的导入语句为:
from .inherited import classes
这里的.代表当前模块(sequences.py)所在的目录(即modules),通过相对路径定位到同级的inherited子包。
注意事项
- 确保
modules和inherited目录下的__init__.py文件存在(你已满足此条件),空文件即可,Python会将包含该文件的目录识别为可导入的包。 - 若使用相对导入,不要单独运行
sequences.py,必须通过main.py导入运行,否则会触发相对导入语法错误。
内容的提问来源于stack exchange,提问作者Gooberton
相关产品推荐
相关产品推荐

