对于“ImportError:无法导入名称 X”或“AttributeError:...(很可能是由于循环导入)”我能做些什么?

新手上路,请多包涵

我有一些代码分布在多个文件中,这些文件尝试相互 import ,如下所示:

主要.py:

 from entity import Ent

实体.py:

 from physics import Physics
class Ent:
    ...

物理.py:

 from entity import Ent
class Physics:
    ...

然后我从 main.py 运行,我得到以下错误:

 Traceback (most recent call last):
File "main.py", line 2, in <module>
    from entity import Ent
File ".../entity.py", line 5, in <module>
    from physics import Physics
File ".../physics.py", line 2, in <module>
    from entity import Ent
ImportError: cannot import name Ent

我假设错误是由于导入 entity 两次 - 一次在 main.py 和后来 physics.py 但我该如何解决这个问题?


另请参阅 在 Python 中使用相互或循环(循环)导入时会发生什么? 有关允许的内容以及导致 WRT 循环导入问题的原因的一般概述。请参阅 为什么循环导入似乎在调用堆栈中更靠前,但在更靠下的位置引发 ImportError? 有关问题发生 原因和方式 的技术细节。

原文由 jsells 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 280
1 个回答

您有循环依赖导入。 physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing .从 entity 模块中删除对 physics 的依赖。

原文由 Teemu Ikonen 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题