Python Class 带有移动导入错误的继承

Python Class Inheritance with a moving import error

我关于堆栈的第一个问题! :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 个关于这个主题的不同视频,但仍然不确定为什么或如何让它正常工作。)(我只是说我试图找到答案,但我现在已经筋疲力尽了,在我真的发疯之前需要一个解决方案!)谢谢,谢谢,谢谢

直到有人告诉我更好的方法,我会做以下...

if __name__ == "__main__":
  from parent_class import Parent
else:
  from modules.parent_class import Parent

TLDR:

运行 带有 -m 标志的 python 文件。

python -m modules.child_class


这个问题是由于误解了 Python 脚本程序和 Python 包程序之间的区别。

如果您正在 运行将 Python 程序作为脚本(运行直接将 Python 文件),那么您可以像已经这样做的那样直接导入:

from parent_class import Parent

但是,如果您构建的 Python 包旨在导入其他程序(例如库或框架),那么您需要使用相对导入。 (听起来 Unittest 运行 将程序作为一个包,但是当您 运行 程序时,您是 运行 将其作为脚本。)

    from .parent_class import Parent
# or
    from modules.parent_class import Parent

如果你正在制作一个包,那么 运行 带有 -m 标志的程序或导入到另一个程序(脚本或另一个包)

python -m main

python -m modules.child_class