【发布时间】:2019-03-01 19:29:20
【问题描述】:
我有四个不同的文件,分别命名为:main.py、vector.py、entity.py 和 physics.py。我不会发布所有代码,只发布导入,因为我认为这就是错误所在(如果你愿意,我可以发布更多)。
main.py:
import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the result of movement
实体.py:
from vector import Vect
from physics import Physics
class Ent:
#holds vector information and id
def tick(self, dt):
#this is where physics changes the velocity and position vectors
vector.py:
from math import *
class Vect:
#holds i, j, k, and does vector math
physics.py:
from entity import Ent
class Physics:
#physics class gets an entity and does physics calculations on it.
然后我从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
我猜测错误是由于两次导入实体造成的,一次在main.py,然后在physics.py,但我不知道解决方法。有人可以帮忙吗?
【问题讨论】:
-
它们的存储位置和目录的目录结构是什么?
-
看看这个在 python 中循环导入的答案:stackoverflow.com/questions/7199466/…
-
一般来说,使用
from <module> import <name>或from <modlue> import *并不是一个好的编码习惯。最好在模块命名空间下导入,以防止覆盖同名引用。 -
@jsells 你应该只调用你的类
Entity和Vector而不是Ent和Vect,没有理由缩短这些名称。是的,使用import vector,然后使用x = vector.Vector(0,0,0)。 -
嘿@Kevin,既然你更了解Java,你对这个2008 article的印象如何,作者的第一句话是指循环依赖是如何“相当普遍的做法”爪哇?
标签: python python-import importerror circular-dependency