首页 > 解决方案 > Python对象列表附加相同的ID

问题描述

我真的很困惑这种工作方式。我有以下课程:

class Square:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def move_to(self, direction):
        if direction == 'Right':
            self.x += 10
            
        if direction == 'Left':
            self.x -= 10
        
        if direction == 'Up':
            self.y -= 10
        
        if direction == 'Down':
            self.y += 10
            
    def __repr__(self):
        return f"Square[x={self.x}, y={self.y}]"

然后我制作这个列表((10, 0) 和 (20, 0) 中的两个方格)并将第一个方格向左“移动”10 步:

square_list = [Square(10, 0), Square(20, 0)]
print(square_list)

square_list[0].move_to("Left")
print(square_list)

一切似乎都很好:

[Square[x=10, y=0], Square[x=20, y=0]]
[Square[x=0, y=0], Square[x=20, y=0]]

但是,当我设置一个包含一个元素的列表,然后将第一个元素附加到同一个列表中以便后者仅移动第一个元素时:

square_list = [Square(10, 0)]
square_list.append(square_list[-1])
print(square_list)

square_list[0].move_to("Left")
print(square_list)

我有一个意外的行为(两个方块向左移动):

[Square[x=10, y=0], Square[x=10, y=0]]
[Square[x=0, y=0], Square[x=0, y=0]]

那是因为这两个元素具有相同的 ID。为什么???我尝试制作一个 Snake Game 算法来移动蛇身的元素,然后移动头部/第一个元素,但这项工作的唯一方法是添加一个新对象 Square 做square_list.append(Square(square_list[-1].x, square_list[-1].y)。还有另一种更清洁的方法吗?

标签: pythonlistoop

解决方案


推荐阅读