5

directory という名前のモジュールと、種という名前の別のモジュールがあります。私が持っている種の数に関係なく、常に1つのディレクトリしかありません。

ディレクトリモジュールには、1つのディレクトリクラスがあります。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

問題は、私のクラスのそれぞれで、その種にアトラス オブジェクトを渡さなければならないことです。別のモジュールからインスタンスを取得するように種に指示するにはどうすればよいですか。

たとえば、クラス Entity を持つ Entity という名前のモジュールに 'atlas' のインスタンスがある場合、数行のコードですべての種に Entity からそのインスタンスを取得するように指示するにはどうすればよいですか?

4

1 に答える 1

8

私があなたを正しく理解していれば、この質問に答えようとしています.Singletonパターンの例である、すべての種のグローバルアトラスを保持するにはどうすればよいですか? このSOの質問を参照してください

これを簡単かつ Python で行う 1 つの方法は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]}]

コードは大幅に改善される可能性がありますが、一般原則は明確になっているはずです。

于 2012-06-08T04:40:01.247 に答える