2012-05-16 20 views
0

我有2個類,一個機器人類來移動單位和一個地圖類來跟蹤他們在哪裏。地圖集中有一個圖集課程和多個機器人課程。我如何在類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歲,剛剛接觸編程。這是一個練習程序,我無法在谷歌或雅虎上找到它。請幫助

回答

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()'實例化'Robot'本身。備用類可以傳遞給初始化器。 –