从不同的模块导入类的实例

时间:2012-06-08 03:45:54

标签: python

我有一个名为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

问题在于,在我的每个课程中,我必须将atlas对象传递给该物种。我怎样才能告诉物种从不同的模块中获取实例。

示例如果我在名为Entity的模块中有一个'atlas'实例,并且有一个Entity类,我怎么能用几行代码告诉所有物种从Entity中获取该实例?

1 个答案:

答案 0 :(得分:6)

如果我理解正确的话,试着回答这个问题:我如何为我的所有物种保留全球地图集,这是Singleton模式的一个例子? See this SO question

这样做的一种方法,简单地说,也就是说,在文件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

然后在您的主脚本中,不同的物种可以通过导入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]}]

代码可以大大改进,但一般原则应该是明确的。