2012-05-16 5 views
0

У меня есть 2 класса, класс робота для перемещения единиц и класс карты, чтобы отслеживать, где они находятся. В атласе есть один класс атласа и несколько классов роботов. Как я могу использовать функцию в Atlas от класса Robot.Как ссылаться на класс, который не унаследован

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()' экземпляр 'самого робота', если бы я пошел этим путем. Альтернативные классы могут быть переданы инициализатору. –