查看: 1284|回复: 3

ImportError: cannot import name X

[复制链接]

11

主题

80

帖子

199

积分

注册会员

Rank: 2

积分
199
发表于 2018-9-18 16:02:25 | 显示全部楼层 |阅读模式
本帖最后由 强人锁男 于 2018-9-18 16:04 编辑

我有四个不同的文件:main,vector,entity和physics。)
main:
  1. import time
  2. from entity import Ent
  3. from vector import Vect
  4. #the rest just creates an entity and prints the result of movement
复制代码

entity:
  1. from vector import Vect
  2. from physics import Physics
  3. class Ent:
  4.     #holds vector information and id
  5. def tick(self, dt):
  6.     #this is where physics changes the velocity and position vectors
复制代码

vector:
  1. from math import *
  2. class Vect:
  3.     #holds i, j, k, and does vector math
  4. physics:
  5. from entity import Ent
  6. class Physics:
  7.     #physics class gets an entity and does physics calculations on it.
复制代码

然后我从main.py运行,我收到以下错误:
  1. Traceback (most recent call last):
  2. File "main.py", line 2, in <module>
  3.     from entity import Ent
  4. File ".../entity.py", line 5, in <module>
  5.     from physics import Physics
  6. File ".../physics.py", line 2, in <module>
  7.     from entity import Ent
  8. ImportError: cannot import name Ent
复制代码

我是Python的新手,但已经使用C ++很长一段时间了。我猜这个错误是由于导入entity两次,一次是在main中,另一次在physics中,,但我不知道如何解决。有人可以帮忙吗?
回复

使用道具 举报

10

主题

72

帖子

180

积分

注册会员

Rank: 2

积分
180
发表于 2018-9-18 16:05:14 | 显示全部楼层
这是循环依赖导入。physics.py从定义entity类之前导入Ent并physics尝试导入entity已经初始化的类。physics从entity模块中删除依赖项。
回复

使用道具 举报

15

主题

97

帖子

310

积分

论坛管理

Rank: 4

积分
310
发表于 2018-10-10 08:10:24 | 显示全部楼层
细节知识点,很不错
回复

使用道具 举报

3

主题

55

帖子

131

积分

注册会员

Rank: 2

积分
131
发表于 2018-10-11 08:20:23 | 显示全部楼层
进来瞅瞅
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表