我有四个不同的文件:main,vector,entity和physics.我不会发布所有代码,只发布导入,因为我认为这就是错误所在.(如果你愿意,我可以发布更多)
主要:
import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the result of movement
Run Code Online (Sandbox Code Playgroud)
实体:
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
Run Code Online (Sandbox Code Playgroud)
向量:
from math import *
class Vect:
#holds i, j, k, and does vector math
Run Code Online (Sandbox Code Playgroud)
物理:
from entity import Ent
class Physics:
#physics class gets an entity …Run Code Online (Sandbox Code Playgroud) 我有两个python模块:
a.py
import b
def hello():
print "hello"
print "a.py"
print hello()
print b.hi()
Run Code Online (Sandbox Code Playgroud)
b.py
import a
def hi():
print "hi"
Run Code Online (Sandbox Code Playgroud)
当我跑步时a.py,我得到:
AttributeError: 'module' object has no attribute 'hi'
Run Code Online (Sandbox Code Playgroud)
错误是什么意思?我如何解决它?
假设我有以下目录结构:
a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
Run Code Online (Sandbox Code Playgroud)
在a包中__init__.py,c导入包.但是c_file.py进口a.b.d.
程序失败,说尝试导入b时不存在.(它确实不存在,因为我们正在进口它.)c_file.pya.b.d
如何解决这个问题呢?
我是 Python 新手,之前我一直在使用像 Swift 这样的语言,其中导入并不是什么大问题:您只是定义了一个新类,并且可以从程序的另一部分访问它。
我不能在 Python 中使用这种方式,因为这里 import 以另一种方式工作:您不能进行循环导入,其中两个文件相互导入。我知道我因为以错误的方式使用语言而面临这个问题,但我不明白如何避免它。
我的意思是,在大多数情况下,您可以通过将两个类合并到一个文件中来解决这个问题,但感觉不对。另外,我发现了诸如“将您的导入语句移动到文件末尾”之类的建议,但这也不是一个好主意。
如果您愿意,我想了解 Python 的哲学。在决定在一个单独的文件中创建一个类时,我应该如何组织我的项目以及我应该以什么为指导?