首页 > 解决方案 > Python:变量更改而不被调用

问题描述

我怀疑将类变量存储在第二个变量中,以便以后调用。这是我的代码(简化为可读):

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],它的值实际上在两者之间变化print()?我修改了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]]

标签: pythonpython-3.xclassoopmethods

解决方案


Player.position是列表,这意味着它是可变类型。如果你把这个列表放在另一个列表中,Python 会引用它,而不是复制。

当您在列表中添加/删除/更改项目时,它会在引用保留的任何地方发生变化。

分配给 时需要制作副本agent.actual。查看copyPython 中的模块或重构代码(提示:tuple是不可变类型)


推荐阅读