Python Class 内的真实副本

Python True Copy Within a Class

出于某种原因,我有一个列表,尽管它是一个明确的深拷贝,但它一直在被修改。它在循环中似乎没有被修改,但是一旦存在就突然被修改了?我一定是遗漏了一些与 Python 的规则和逻辑有关的东西,但我一辈子都弄不明白。

def all_possible_states(self):
    #creates many variations of a board from the available set of moves
    to_return = [] #list of possible board states to return
    #print(self.availible_moves)
    list_to_copy = copy.deepcopy(self.availible_moves)
    for item in self.availible_moves:
        print('loop')
        
        #append possible board state to list. set of availible moves for that board is one less. Done by removing item from that move list
        to_return.append(board(self.player, copy.deepcopy(self.board.copy()), list_to_copy, self.plays, self.score, copy.deepcopy(item)))
        
        #print(item)
        print( self.avalible_moves) #shows the total set of moves. This is unmodified whenever it prints
        print(list_to_copy)#deep copy of the original list. This is unmodified when it prints
        print(to_return[len(to_return) - 1].availible_moves) #List of moves left availible for the board, this slowly shrinks for some reason each loop
    
    
    print(self.availible_moves) #this is the original list, but it's not basically been cut all the way down for some reason
    return to_return

注意,局部变量list_to_copy是deepcopy,不是self.availible_moves。您正在保存 self.availible_moves 的深层副本,并将其存储在您定义的 list_to_copy 变量中。 list_to_copy 永远不会像 deepcopy 预期的那样改变。我不确定您要做什么,但如果您愿意,最后您可以将 self.availible_moves 重置为等于 list_to_copy,然后就好像它从未改变过一样。

编辑:

实际上,我认为你有一个拼写错误,请注意你 print(self.avalible_moves) 并且你说它没有改变,而真正改变的是 self.availible_moves。注意第一个表达式中的额外字母 i。这绝对是你的问题之一。