在Python中,为什么我的DeepCopy仍然具有其值的变化?
我在 python 中创建了一个类,并且尝试创建它的 deepCopy,但是当我修改原始类时,“deepCopy”的值仍然发生了变化。
class boardState():
def __init__(self, board, orient,actions,expl):
self.board
self.orientations = orient
self.actions = actions
self.explored = expl
def __deepcopy__(self):
return boardState(self.board, self.orientations, self.actions, self.explored)
board = []
orientations = {} #this stores the orientations of the cars in the current problem.
actions = [] #this is a list of the moves made to get to this current position.
explored = []
^ 上面是我正在使用并想要复制的类。
referencestate = copy.deepcopy(state)
print(id(referencestate))
print(id(state))
^ 运行此行后,显示它们具有相同的 id,我想让它们独立。
任何帮助将不胜感激!
I have made a class in python and I am trying to create a deepCopy of it, however the 'deepCopy' still has its values changed when I modify the original.
class boardState():
def __init__(self, board, orient,actions,expl):
self.board
self.orientations = orient
self.actions = actions
self.explored = expl
def __deepcopy__(self):
return boardState(self.board, self.orientations, self.actions, self.explored)
board = []
orientations = {} #this stores the orientations of the cars in the current problem.
actions = [] #this is a list of the moves made to get to this current position.
explored = []
^ above is the class that I am using and want to make a copy of.
referencestate = copy.deepcopy(state)
print(id(referencestate))
print(id(state))
^ after running this line, it's shown that they have the same id, I would like to make them Independant.
Any help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这个deepcopy只是得到了一个新的boardState类,但是id(state.board) = id(referencestate.board),因为在创建class时直接使用原始对象。
如果不想更改原始值,请不要直接传递参数。使用它们的副本。你可以尝试使用 ->state=boardState(board[:], dict.copy(orientations), actions[:],explored[:]) #this 使用shallow。
看看下面的代码->
尝试跑步
I think this deepcopy just get a new class for boardState but the id(state.board) = id(referencestate.board), because the original object is used directly when creating the class .
If you do not want to change the original value, do not pass the parameter directly.Use a copy of them. You can try to use ->state=boardState(board[:], dict.copy(orientations), actions[:], explored[:]) #this use shallow.
Take a look at the code below ->
try running