python对象更改属性

2024-09-24 22:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个坦克游戏,我有坦克和子弹。当我开火时,执行以下方法:

def newshot(self,tank):
    shot = bullet()
    shot.loc = tank.loc
    shot.speed = tank.direction
    self.shots.append(shot)

loc是显示位置[x,y]的列表,speed和direction是显示速度[dx,dy]的列表。你知道吗

为了移动每个子弹,速度向量被添加到for循环中的位置。但是每当我改变子弹的位置时,我的坦克的位置也会改变(我在for循环前后打印了一个坦克的位置)。 我解决问题的方法是

shot.loc = tank.loc

是的

shot.loc = [tank.loc[0],tank.loc[1]]

我的问题是区别在哪里?


Tags: 方法self游戏列表fordef速度loc
3条回答

你需要deepcopy这个列表。即:

import copy
shot.loc = copy.deepcopy(tank.loc)

下面是它的工作原理:

a = [[1, 2, 3], [4, 5, 6]]
b = a
a[0][1] = 10
print a
# [[1, 10, 3], [4, 5, 6]]
print b   # b changes too -> Not a deepcopy.
# [[1, 10, 3], [4, 5, 6]]


import copy
b = copy.deepcopy(a)
a[0][1] = 9
print a
#[[1, 9, 3], [4, 5, 6]]
print b    # b doesn't change -> Deep Copy
#[[1, 10, 3], [4, 5, 6]]

您复制了引用而不是值,这意味着两个变量指向同一个对象。你知道吗

https://docs.python.org/2/library/copy.html

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

tank.loc列表复制到shot.loc的最简单方法是对整个列表进行切片:

shot.loc = tank.loc[:]

但其他有效的建议请参见https://stackoverflow.com/a/2612815/768176。你知道吗

使用时:

shot.loc = tank.loc

shot.loctank.loc是对同一列表的引用。你知道吗

要复制列表,请使用:

shot.loc = tank.loc[:]

相关问题 更多 >