保存对象的深拷贝,然后修改并保存另一个拷贝?

0 投票
1 回答
501 浏览
提问于 2025-04-16 05:12

我有一个叫做“GameBoard”的类,我正在对它进行搜索。我想把当前的游戏棋盘保存到一个列表里,然后改变棋盘的状态,再把这个新的棋盘也保存到列表里,依此类推(这样我就能得到随着游戏进行而逐渐变化的棋盘版本)。

我现在是用copy.deepcopy来实现这个功能,但似乎没有成功。以下是我的代码示例:

    moves = [] # just for reference.  this has at least one value in it by the time the while loop hits.
    while winner is False and len(moves) > 0:
        g_string = gb.to_string()
        if g_string == win_string:
            winner = True
            break

        possibilities = gb.legal_moves(visited) # returns a list of possible moves to take

        if len(possibilities) > 0:
            moves.append(copy.deepcopy(gb))
            gb.perform(possibilities[0]) # this modifies gb, according to the gameplay move.
            # snipped, for brevity.

如果在经过100次循环后,我打印moves,我会得到100个完全相同的对象。如果我在每次添加之前打印这个对象,它们在添加时确实是不同的。

为了更清楚,我想要这些对象的副本(可以用来做一些图形操作,比如进行深度优先搜索和广度优先搜索)。

这是我GameBoard类的更多内容:

class GameBoard:
    number_of_rows = 3
    rows = []
    global random_puzzle

    def __init__(self, setup):
            #some code.  fills in the rows. adds some things to that list. etcetc..
            # more code

1 个回答

0

你的代码在简单的字典对象上是有效的:

seq = 1
a_dict = {}
moves = []
while seq < 4:
 a_dict['key' + str(seq)] = 'value' + str(seq)
 moves.append(copy.deepcopy(a_dict))
 seq = seq + 1

print moves

但是在你的对象中,深拷贝(deepcopy)没有复制到你的游戏板的内容。

你的游戏板数据是不是存储在对象外面?这样的话,可能只是复制了一个指向它的指针。你保存的是棋盘的哪个状态,是第一个状态还是最后一个状态?能不能提供更多关于你对象结构的细节?


编辑:试着添加你自己的 getstate/setstate 方法,这样可以告诉深拷贝哪些数据需要在实例之间复制。例如,如果你的 rows 数组包含了游戏板:

def __getstate__(self): 
    return self.rows

def __setstate__(self, rows): 
    self.rows = rows 

撰写回答