我有一个名为directory的模块和另一个名为species的模块.无论我有多少种,总会有一个目录.
在目录模块中,我有1个目录类.在物种模块内部,我有许多不同的物种类别.
#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
Run Code Online (Sandbox Code Playgroud)
问题是,在我的每个类中,我必须将atlas对象传递给该物种.我怎样才能告诉物种从不同的模块中获取实例.
例如,如果我在一个名为Entity的模块中有一个'atlas'实例,并且有一个Entity类,我怎么能用几行代码告诉所有物种从Entity中获取该实例?
试着回答这个问题,如果我理解正确的话:我如何为我的所有物种保留全球地图集,这是Singleton模式的一个例子?看到这个问题.
简单地和Python地,这样做的一种方法是在directory.py
包含所有与目录相关的代码和全局atlas
变量的文件中包含模块:
atlas = []
def add_to_world(obj, space=[0,0]):
species = {'obj' : obj.object_species,
'name' : obj.name,
'zone' : obj.zone,
'space' : space}
atlas.append( species )
def remove_from_world(obj):
global atlas
atlas = [ species for species in atlas
if species['name'] != obj.name ]
# Add here functions to manipulate the world in the directory
Run Code Online (Sandbox Code Playgroud)
然后在您的主脚本中,不同的物种可以atlas
通过导入directory
模块来引用该全局,因此:
import directory
class Species(object):
def __init__(self, object_species, name, zone = 'forest'):
self.object_species = object_species
self.name = name
self.zone = zone
directory.add_to_world(self)
class Llama(Species):
def __init__(self, name):
super(Llama, self).__init__('Llama', name)
class Horse(Species):
def __init__(self, name):
super(Horse, self).__init__('Horse', name, zone = 'stable')
if __name__ == '__main__':
a1 = Llama(name='LL1')
print directory.atlas
# [{'obj': 'Llama', 'name': 'LL1', 'zone': 'forest', 'space': [0, 0]}]
a2 = Horse(name='H2')
print directory.atlas
# [{'obj': 'Llama', 'name': 'LL1', 'zone': 'forest', 'space': [0, 0]},
# {'obj': 'Horse', 'name': 'H2', 'zone': 'stable', 'space': [0, 0]}]
directory.remove_from_world(a1)
print directory.atlas
# [{'obj': 'Horse', 'name': 'H2', 'zone': 'stable', 'space': [0, 0]}]
Run Code Online (Sandbox Code Playgroud)
代码可以大大改进,但一般原则应该清楚.
归档时间: |
|
查看次数: |
5677 次 |
最近记录: |