我有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岁,是编程新手。这是一个练习程序,我无法在谷歌或雅虎找到这个。请帮忙
答案 0 :(得分:5)
您只能访问您引用的对象的方法。也许您应该将Atlas
的实例传递给初始化程序。
class Robot():
def __init__(self, rbt, atlas):
self.atlas = atlas
...
self.atlas.add_robot(rbt)
答案 1 :(得分: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()