Python:变量更改而不被调用
我怀疑是否将类变量存储在第二个变量中,以便以后调用。 这是我简化为可读的代码:Python:变量更改而不被调用,python,python-3.x,class,oop,methods,Python,Python 3.x,Class,Oop,Methods,我怀疑是否将类变量存储在第二个变量中,以便以后调用。 这是我简化为可读的代码: class Agent(object): def __init__(self): self.actual = [] class Play(object): def __init__(self): self.x = 0.45 * 400 self.y = 0.5 * 400 self.position = [] self
class Agent(object):
def __init__(self):
self.actual = []
class Play(object):
def __init__(self):
self.x = 0.45 * 400
self.y = 0.5 * 400
self.position = []
self.position.append([self.x, self.y])
self.x_change = 20
self.y_change = 0
def do_move(self, move, x, y):
move_array = [self.x_change, self.y_change]
if move == 1 and self.x_change == 0: # right
move_array = [20, 0]
self.x_change, self.y_change = move_array
self.x = x + self.x_change
self.y = y + self.y_change
self.update_position(self.x, self.y)
def update_position(self, x, y):
self.position[-1][0] = x
self.position[-1][1] = y
def run():
agent = Agent()
player1 = Play()
agent.actual = [player1.position]
print(agent.actual[0])
i = 1
player1.do_move(i, player1.x, player1.y)
print(agent.actual[0])
run()
>> [[180.0, 200.0]]
>> [[200.0, 200.0]]
这是我无法理解的。为什么,如果agent.actual存储了player.position,并且在agent.actual=[player1.position]之后它没有被修改,那么它的值实际上在两次打印之间发生了变化?
我修改了player.position,但没有修改agent.actual,这意味着它应该保持不变。我搞不懂
编辑:
按照建议,我尝试了以下方法:
agent.actual = player1.position.copy()
agent.actual = player1.position[:]
agent.actual= list(player1.position)
import copy
agent.actual = copy.copy(player1.position)
agent.actual = copy.deepcopy(player1.position)
与以前一样,所有这些方法始终返回两个不同的值:
>> [[180.0, 200.0]]
>> [[200.0, 200.0]]
Player.position是list,这意味着它是可变类型。如果将此列表放在另一个列表中,Python将引用它,而不是复制它
在列表中添加/删除/更改项目时,引用所在的位置都会更改
分配给agent.actual时,需要制作一份副本。查看Python中的复制模块或重构代码提示:tuple是不可变类型agent.actual是一个包含对另一个列表的引用的列表,该列表是可变的。因此,对player1.position的更改将反映在agent.actual中。如果你不希望出现这种行为,请参阅dupe,了解如何创建副本。谢谢,我终于明白了。很抱歉重复,我之所以这样做是因为我不知道Python是否使用引用而不是副本,不是因为我没有准确地查找它。@jonrsharpe我按照您提到的问题中的建议进行了尝试,但正如您在我的编辑中所看到的,结果并没有什么不同。谢谢,正如您在我的编辑中所看到的,我尝试了您建议的复制模块,但它不起作用。@MauroComi不在列表中保留位置,使用元组。复制清单会在极端情况下造成麻烦。元组是不可变的。