2012-06-08 3 views
2

나는 디렉토리라는 이름의 모듈과 종이라는 모듈을 가지고 있습니다. 내가 가지고있는 종의 수에 관계없이 항상 하나의 디렉토리 만있을 것입니다.다른 모듈에서 클래스 인스턴스 가져 오기

디렉토리 모듈에는 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 인 모듈에서 'atlas'인스턴스가있는 경우, 몇 줄의 코드를 사용하여 모든 종류의 인스턴스에서 Entity 인스턴스를 가져올 수 있습니까?

+0

귀하의 질문에 이해하기 어렵습니다. 다른 것을 가져 오는 것과 마찬가지로 인스턴스를 가져올 수 있습니다. 모듈 Entity가 인스턴스 x를 생성하면 다른 모듈에서 'import Entity.x'를 실행하여 해당 인스턴스를 가져올 수 있습니다. – BrenBarn

+0

@ [user1082764] [이 질문 (http://stackoverflow.com/q/10952973/1290420)]을 참조하십시오. 관련/동일한 질문을 상호 참조하는 것이 정중합니다. – gauden

답변

5

이 질문에 대한 대답을 시도해보십시오. 올바르게 이해한다면 : 내 모든 종에 대한 글로벌 아틀라스를 어떻게 유지해야합니까? 싱글 톤 패턴의 예는 무엇입니까? See this SO question.

이 간단하고, Pythonically을하는 한 가지 방법은, 모든 디렉토리 관련 코드 및 글로벌 atlas 변수가 포함 된 파일 directory.py에 모듈을 가지고

입니다 : 메인 스크립트에 다음

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 

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

코드는 많이 개선 될 수 있지만 일반적인 원칙은 명확해야한다 : 다른 종 따라서, directory 모듈을 가져 글로벌 atlas 것을 참조 할 수있다.

관련 문제