ImportError:无法导入名称X.
我有四个不同的文件名为:主,vector,实体和物理。 我不会发布所有的代码,主要是import,因为我认为这是错误的地方。 但如果你想,我可以发布更多。
主要:
import time from entity import Ent from vector import Vect #the rest just creates an entity and prints the result of movement 实体:
 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 
向量:
 from math import * class Vect: #holds i, j, k, and does vector math 
物理:
 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 
我对python非常陌生,但是很久以来一直和C ++一起工作。 我猜测原因是从导入实体两次,一次在主要,后来在物理,但我不知道一个解决方法。 任何人帮助?
 你有循环依赖import。  physics.py是在Ent类被定义之前从entity导入的,而physics尝试导入已经初始化的entity 。 从entity模块中删除对physics的依赖。 
虽然你一定要避免循环依赖,你可以推迟导入python。
例如:
 import SomeModule def someFunction(arg): from some.dependency import DependentClass 
这(至less在某些情况下)会绕过这个错误。
 这是一个循环依赖。 可以在不对代码进行任何结构修改的情况下解决。 出现这个问题的原因是因为在vector ,要求entity立即可用,反之亦然。 这个问题的原因是你要求在准备好之前访问模块的内容 – 通过使用from x import y 。 这和本质上是一样的 
 import x y = xy del x 
Python能够检测循环依赖并防止导入的无限循环。 基本上所有这些都是为模块创build一个空的占位符(即它没有内容)。 一旦编译循环依赖模块,它将更新导入的模块。 这是这样的作品。
 a = module() # import a # rest of module a.update_contents(real_a) 
 要使python能够处理循环依赖,只能使用import x style。 
 import x class cls: def __init__(self): self.y = xy 
 由于您不再引用顶层模块的内容,因此python可以编译模块,而不必实际访问循环依赖的内容。 顶层是指在编译期间执行的行,而不是函数的内容(例如, y = xy )。 访问模块内容的静态或类variables也会导致问题。 
我刚刚得到这个错误,出于不同的原因…
 from my_sub_module import my_function 
 主脚本有Windows行结尾。  my_sub_module有UNIX行尾。 改变他们是一样的问题。 他们还需要有相同的字符编码。 
  Python是区分大小写的,所以entity != Entity 。 我build议你在你的导入中将entity的shell改为Entity 。 这将解决您的问题。 
你的主要应该是这样的主要:
 import time from entity import * from vector import * #the rest just creates an entity and prints the result of movement