gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:55 24 4
gpt4 key购买 nike

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

问题是,在我的每个类(class)中,我都必须将 map 集对象传递给该物种。我怎样才能告诉物种从不同的模块中获取实例。

例如,如果我在名为 Entity 的模块中有一个“atlas”实例,带有一个 Entity 类,我如何通过几行代码告诉所有物种从 Entity 中获取该实例?

最佳答案

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

一种简单且符合 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

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

代码可以改进很多,但一般原则应该很清楚。

关于python - 从不同的模块导入类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10942831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com