2012-05-16 4 views
0

두 개의 클래스, 유닛을 이동하는 로봇 클래스와 맵 클래스를 사용하여 위치를 추적합니다. 아틀라스에는 하나의 아틀라스 클래스와 여러 로봇 클래스가 있습니다. Robot 클래스의 Atlas에서 함수를 어떻게 사용할 수 있습니까?상속되지 않는 클래스를 참조하는 방법

class Atlas: 
    def __init__(self): 
     self.robots = [] 
     self.currently_occupied = {} 

    def add_robot(self, robot): 
     self.robots.append(robot) 
     self.currently_occupied = {robot:[]} 

    def all_occupied(self): 
     return self.currently_occupied 

    def occupy_spot(self, x, y, name): 
     self.currently_occupied[name] = [x, y] 


class Robot(): 
    def __init__(self, rbt): 
     self.xpos = 0 
     self.ypos = 0 
     atlas.add_robot(rbt) #<-- is there a better way than explicitly calling this atlas 
     self.name = rbt 

    def step(self, axis): 
     if axis in "xX": 
      self.xpos += 1 
     elif axis in "yY": 
      self.ypos += 1 
     atlas.occupy_spot(self.xpos, self.ypos, self.name) 

    def walk(self, axis, steps=2): 
     for i in range(steps): 
      self.step(axis) 



atlas = Atlas() #<-- this may change in the future from 'atlas' to 'something else' and would break script 
robot1 = Robot("robot1") 
robot1.walk("x", 5) 
robot1.walk("y", 1) 
print atlas.all_occupied() 

저는 14 세이며 프로그래밍에 익숙하지 않습니다. 이것은 연습 프로그램이고 나는 google 또는 yahoo에 이것을 찾아 낼 수 없다. 제발 도와주세요

답변

5

참조 할 수있는 개체의 메서드에만 액세스 할 수 있습니다. 아마도 Atlas의 인스턴스를 이니셜 라이저에 전달해야합니다.

class Robot(): 
    def __init__(self, rbt, atlas): 
    self.atlas = atlas 
    ... 
    self.atlas.add_robot(rbt) 
+0

나는 하나의지도 책에서 여러 로봇을 필요로 할 수 있습니다. 이 여러 아틀라스 개체를 만들까요? – user1082764

+3

아니요. 외부에 하나의'Atlas' 객체를 만들고 그것을 생성자에 전달하고 있습니다. 이니셜 라이저는 참조 사본 만 작성합니다. –

0

여기 하나의 방법 당신은

class Atlas: 
    def __init__(self): 
     self.robots = [] 
     self.currently_occupied = {} 

    def add_robot(self, robot): 
     self.robots.append(robot) 
     self.currently_occupied[robot.name] = [] 
     return robot 

    def all_occupied(self): 
     return self.currently_occupied 

    def occupy_spot(self, x, y, name): 
     self.currently_occupied[name] = [x, y] 


class Robot(): 
    def __init__(self, rbt): 
     self.xpos = 0 
     self.ypos = 0 
     self.name = rbt 

    def step(self, axis): 
     if axis in "xX": 
      self.xpos += 1 
     elif axis in "yY": 
      self.ypos += 1 
     atlas.occupy_spot(self.xpos, self.ypos, self.name) 

    def walk(self, axis, steps=2): 
     for i in range(steps): 
      self.step(axis) 



atlas = Atlas() 
robot1 = atlas.add_robot(Robot("robot1")) 
robot1.walk("x", 5) 
robot1.walk("y", 1) 
print atlas.all_occupied() 
+0

이렇게하면 로봇이'Atlas.add_robot()'을 인스턴스화합니다. 대체 클래스를 초기화 프로그램에 전달할 수 있습니다. –

관련 문제