目前我有一个这样的python文件(非常简化):
u = 30
colors = ('blue', 'red')
grid = [0, 1]
class entity:
def __init___(self, x, color)
self.x = x
self.color = color
def move(self):
print(grid[self.x + 1], self.color)
foo = entity(0, 'blue')
bar = entity(0, 'red')
while true:
foo.move()
bar.move()
我试着把它分开,我得到了这个:
# initialisation.py
u = 30
colors = ('blue', 'red')
# grid_map.py
from initialisation import u, colors
grid = [0, 1]
# classes.py
from map import u, colors, grid # or *
class entity:
def __init___(self, x, color)
self.x = x
self.color = color
def move(self):
print(grid[self.x + 1], self.color)
# objects.py
from classes import u, colors, grid, entity # or *
foo = entity(0, 'blue')
bar = entity(0, 'red')
# main.py
from objects import u, colors, grid, entity, foo, bar # or *
while true:
foo.move()
bar.move()
现在,我觉得我应该以一种不是从一个文件导入到下一个文件的导入链的方式导入,但我不确定确切的方法。
(希望这是一个最小的,可复制的例子)
作为一个链导入是没有用的,除非在非常特殊的实例中,模块在导入的对象或类上添加或定义功能。由于您没有在main.py
中使用u
,colors
,grid
或entity
,因此根本没有理由导入它们。
和如果需要导入,则从定义的文件中导入,而不是从objects
中导入。
在objects.py
中,您只需要从classes
中导入entity
,而在classes
中,您只需要从map
中导入grid
(顺便说一句,map
是一个坏名字,因为它遮蔽了内部map
函数)。
不需要导入你不使用的符号——你不需要考虑你导入的模块需要什么;模块自己负责。
(另一个小问题;类名应该有TitleCase,所以Entity
将是正确的大写(我也建议一个更好的类名,因为Entity
并没有真正说太多))(它是True
,而不是true
)。