Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import instance of class from a different module

Tags:

python

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 i have 1 directory class. Inside the Species module i have many different species classes.

#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

The problem is that in each of my classes i have to pass the atlas object to that species. How can i just tell the species to get an instance from a different module.

Example if i have an instance of 'atlas' in module named Entity with a class Entity, how can i tell all species with a few lines of code to grab that instance from Entity?

like image 660
user1082764 Avatar asked Jun 08 '12 03:06

user1082764


People also ask

How do I import an instance of a class in Python?

Importing a specific class by using the import command You just have to make another . py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.

Can you import a class from another file in Python?

The import statement allows us to import code from other files or modules into the current file. You can consider it as a link that allows us to access class properties or methods from other files and use them.

Can a module import another module?

Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

How can I import modules if file is not in same directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.


1 Answers

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.

like image 64
daedalus Avatar answered Oct 12 '22 03:10

daedalus