我有一个名为directory的模块和另一个名为species的模块。不管我有多少种,总会有一个目录。
在目录模块中,我有一个目录类。在物种模块中,我有许多不同的物种类。
#module named directory
class directory:
def __init__(self):
...
def add_to_world(self, obj, name, zone = 'forrest', space = [0, 0]):
...
#module named species
class Species (object):
def __init__(self, atlas):
self.atlas = atlas
def new(self, object_species, name, zone = 'holding'):
self.object_species = object_species
self.name = name
self.zone = zone
self.atlas.add_to_world(object_species, name)
class Lama(Species):
def __init__(self, name, atlas, zone = 'forrest'):
self.new('Lama', name)
self.at = getattr(Entity, )
self.atlas = atlas
问题是,在我的每个类中,我都必须将atlas对象传递给该物种。我怎么能告诉物种从另一个模块获取一个实例。
例如,如果我在一个名为Entity的模块中有一个带有类实体的“atlas”实例,我如何用几行代码告诉所有物种从实体中获取该实例?
试图回答这个问题,如果我理解正确的话:我如何为我所有的物种保存一个全球地图集,一个单子模式的例子?See this SO question。
一种简单而可行的方法是在文件
directory.py
中包含所有与目录相关的代码和全局atlas
变量的模块:然后在您的主脚本中,不同的物种可以通过导入
directory
模块引用该全局atlas
,从而:代码可以得到很大的改进,但一般原则应该是明确的。
相关问题 更多 >
编程相关推荐