从不同的modu导入类的实例

2024-04-29 14:28:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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”实例,我如何用几行代码告诉所有物种从实体中获取该实例?


Tags: 模块实例nameself目录zoneobjectinit
1条回答
网友
1楼 · 发布于 2024-04-29 14:28:55

试图回答这个问题,如果我理解正确的话:我如何为我所有的物种保存一个全球地图集,一个单子模式的例子?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

然后在您的主脚本中,不同的物种可以通过导入directory模块引用该全局atlas,从而:

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]}]

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

相关问题 更多 >