python - 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]]
解决方案
Player.position
是列表,这意味着它是可变类型。如果你把这个列表放在另一个列表中,Python 会引用它,而不是复制。
当您在列表中添加/删除/更改项目时,它会在引用保留的任何地方发生变化。
分配给 时需要制作副本agent.actual
。查看copy
Python 中的模块或重构代码(提示:tuple
是不可变类型)
推荐阅读
- javascript - axios get函数在get方法中带有参数,当它为null或为空时导致404错误
- angular - 为什么 PWA angular 8 应用程序收到 403 webmanifest GET 错误
- javascript - Immutable.js 不按值比较
- powershell - 以参数为条件
- swift - UI对象在链接到swift文件时创建实例?
- oracle - Sqoop 因无法识别的参数而失败
- azure-iot-hub - 使用事件网格的 IoT 中心事件延迟
- office-js - Outlook 客户端加载项:链接和 JS 重定向到其他域,打开新的浏览器选项卡
- mysql - iReport中的员工考勤日历报表设计
- wordpress - 我可以使用固定布局创建自定义 Woocommerce 结帐吗