我有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歲,剛剛接觸編程。這是一個練習程序,我無法在谷歌或雅虎上找到它。請幫助
我需要在一個單一的圖集多個機器人。這不會創建多個地圖集對象? – user1082764
不可以。您正在外部創建一個「Atlas」對象,並將其傳遞給構造函數。初始化程序僅創建參考的副本。 –