【发布时间】:2021-05-16 04:19:48
【问题描述】:
我的第一个问题! :D
当我尝试吃蛋糕并同时吃它时,我似乎遇到了问题。 我已经删除了所有代码,因为我不认为这是问题的一部分。
我有以下目录结构:
master/
- main.py
- modules/
- parent_class.py
- child_class.py
- __init__.py
在 parent_class.py 中:
class Parent:
pass
在 child_class.py 中:
from modules.parent_class import Parent
class Child(Parent)
pass
if __name__ == "__main__":
child = Child()
child.do_stuff()
在 main.py 中:
from modules.child_class import Child
child = Child()
child.do_stuff()
我认为我遇到的问题与我没有正确理解 sys.path 有关。
当我运行 main.py 时没有错误。 但是,当我尝试运行 child_class.py 以进行测试时,出现以下错误...
Traceback (most recent call last):
File "child_class.py", line 1, in <module>
from modules.parent_class import Parent
ModuleNotFoundError: No module named 'modules'
当我将 child_class.py 更改为此错误时:
from parent_class import Parent
class Child(Parent)
pass
if __name__ == "__main__":
child = Child()
child.do_stuff()
但是现在当我运行 main.py 时,我得到了这个错误:
Traceback (most recent call last):
File "c.../main.py", line 1, in <module>
from modules.child_class import Child
File "...\child_class.py", line 1, in <module>
from parent_class import Parent
ModuleNotFoundError: No module named 'parent_class'
如果每次都必须更改导入行,如何进行单元测试? 预先感谢您的良好解释。 (我已经阅读了很多关于导入、包和模块的文档,观看了关于这个主题的 10 个不同的视频,但仍然不确定为什么或如何使它正常工作。)(我只是说我试图找到答案,但是我现在已经筋疲力尽了,需要一个解决方案才能真正发疯!)谢谢,谢谢,谢谢
【问题讨论】:
-
是的,这是我后来通过另一个来源发现的。我忘了在哪里。这是一个真正的痛苦弄清楚。我将在下面为我的问题写一个更好的答案。不过感谢您的帮助!
标签: python python-3.x inheritance import modulenotfounderror