【问题标题】:Python Class Inheritance with a moving import error带有移动导入错误的 Python 类继承
【发布时间】: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


【解决方案1】:

在有人告诉我更好的方法之前,我将执行以下操作...

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

【讨论】:

    【解决方案2】:

    TLDR:

    使用 -m 标志运行 python 文件。

    python -m modules.child_class


    此问题是由于误解了 Python Script 程序和 Python Package 程序之间的区别造成的。

    如果您将 Python 程序作为脚本运行(直接运行 Python 文件),那么您可以像以前一样直接导入:

    from parent_class import Parent
    

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

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

    如果您正在制作一个包,则使用 -m 标志运行该程序或导入另一个程序(脚本或另一个包)

    python -m 主要

    python -m modules.child_class

    【讨论】:

    • 谢谢。很好的答案
    猜你喜欢
    • 2016-05-12
    • 2021-03-21
    • 2021-02-14
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2018-03-10
    相关资源
    最近更新 更多