0

I was working with Python deep copy trying to create a total copy of original object, but the deep copy didn't seem to create a copy. It still shares the same reference with original object, which is not desired

Here's the code. I have a class Board, the instance of which I want to deep copy.

import copy
class Board:
    xpos = None
    opos = None
    count = None
    status = []

    def __init__(self, size):
        self.xpos=[0,0]
        self.opos=[size-1,size-1]
        self.count = size*size-2
        for i in range(size):
            tmp = ['-']*size
            self.status.append(tmp)
        self.status[0][0] = 'X'
        self.status[size-1][size-1]= 'O'

Somewhere in another function I want to call

board=Board()
localboard=copy.deepcopy(board)
# then do modification to local board....
# but it seems the old board is also affected. This is so weird since
# I am already using deep copy. 

So how can I create a deep copy of the old board? I don't want to share any reference, since I will do modification on the local one and want to keep the old intact..

AndyG
  • 39,700
  • 8
  • 109
  • 143
Daniel
  • 1,484
  • 5
  • 24
  • 42

1 Answers1

1

You should remove the following from the Board definition:

xpos = None
opos = None
count = None
status = []

and add the following to its __init__():

self.status = []

Otherwise all your instances share the same status, which is an attribute of the class, not of the instance.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Big thanks, I think it's the my fault of messing up with instance variable and class variable – Daniel Mar 23 '13 at 16:00