如何更改另一个类函数中的类变量



我需要分配self。current_location从类Robot到self。位置在类网格,但我失败了,有我的代码:

class Grid:
def __init__(self,size=10,location=(0,0)):
self.size=int(size)
self.location=tuple(location)
# self.grid_space=[self.size*['-']]*self.size
# print(self.grid_space)
self.grid_space=[]
for i in range(self.size):
self.grid_space.append(self.size*['-'])
def __str__(self):
self.grid_space[self.location[0]][self.location[1]]="R"
strrep=''
for i in range(self.size):
strrep+=" ".join(self.grid_space[i])+'n'
return strrep
def update(self,new_location):
self.new_location=tuple(new_location)
if self.location==new_location:
return self.location
else:
self.location=new_location
return self.location
def get_location(self):
return self.location
class Robot(Grid):
def __init__(self,modelname,current_location=(0,0)):
self.modelname=str(modelname)
self.grid_space=[]
self.current_location=tuple(current_location)
for i in range(10):
self.grid_space.append(10*['-'])
def __str__(self):
return Grid().__str__()
def move(self,destination):
self.destination=tuple(destination)
self.current_location=self.destination
self.current_location=Grid().location

def main():
print("Test the Grid object...")
my_grid = Grid()
print(f"Location : {my_grid.get_location()}")
my_grid.update((5,5))
print(my_grid)
print()
# create Robot object and test functions
print("Test the Robot object...")
my_robot = Robot("Generic")
print("Initial position")
print(my_robot)
print("Position after move")
my_robot.move((9,9))
print(Grid().location)
if __name__ == '__main__':
main()

你们能告诉我怎么进入自我吗?位置并将其更改为"移动"后的current_location ?

通常您不希望这样做,因为这会破坏类的封装。你可以为Grid类创建一个单元数组,然后将Robot单元添加到Grid中,网格可以读取机器人的位置,因此它知道机器人应该在网格中的位置,并且机器人可以"移动"。使用自己的函数。这样做将导致Robot更新它自己的当前位置属性,然后地图可以在需要时询问机器人的位置。

最新更新