Import instance of class from a different module

后端 未结 1 1416
栀梦
栀梦 2020-12-19 13:02

I have a module named directory and another module named species. There will always only be one directory no matter how many species i have.

In the directory module

相关标签:
1条回答
  • 2020-12-19 13:33

    Trying to answer this question, if I understand you correctly: how do I keep a global atlas for all my species, an example of the Singleton pattern? See this SO question.

    One way of doing this, simply, and Pythonically, is to have module in a file directory.py that contains all the directory-related code and a global atlas variable:

    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
    

    Then in your main script the different species could reference that global atlas by importing the directory module, thus:

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

    The code can be much improved, but the general principles should be clear.

    0 讨论(0)
提交回复
热议问题