python - 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)
。还有另一种更清洁的方法吗?
解决方案
推荐阅读
- c# - 查找自变量更改以来的时间
- linux-kernel - 为什么在linux内核中声音驱动代码单独放在/sound而不是/driver
- java - 使用带有 swagger2 的 spring 部署我的应用程序时
- authentication - Razor Pages .NET Core 2.1 集成测试后身份验证
- python - Ubuntu 14.04 和 Python 2.7:如何解决 PIP 安装问题?
- mysql - 需要:帮助将 MSSQLSvr 递归查询转换为 MySQL SQL
- spring-boot - 春季java邮件问题
- sqlite - SQLite generate_series 缺失
- android - 如何勾勒出矢量可绘制对象的轮廓?
- android - 关于 Java 代码转换为与 Firebase 相关的 Kotlin 的问题