我有一些代码分布在多个文件中,这些文件尝试相互 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 许可协议
您有循环依赖导入。
physics.py
is imported fromentity
before classEnt
is defined andphysics
tries to importentity
that is already initializing .从entity
模块中删除对physics
的依赖。