-1

I have the following class

class CommandList( HasTraits ):

    command_nr = Int    

    command_code = Int    

    command_name = Str

    status = Int       

    settings = None #It will be a list[dic{list[]}]

I'm usind copy.deepcopy to clone the class

a = copy.deepcopy(b)

but when I'm changing the settings variable in a than it effects the b variable. It seems that the deepcopy didn't clone this variable. I read that it is possible to override the __deepcopy__ function. Is it a good idea? How can I do that?

mgilson
  • 300,191
  • 65
  • 633
  • 696
Mokus
  • 10,174
  • 18
  • 80
  • 122
  • 1
    Can you show your actual code? I suspect that the problem is that you're using mutable class attributes instead of instance attributes – mgilson Feb 15 '13 at 16:03
  • 7
    Are you trying to clone a class or a class instance ? – Jonathan Vanasco Feb 15 '13 at 16:04
  • 2
    [duplicate](http://stackoverflow.com/questions/1933784/how-do-you-clone-a-class-in-python) [duplicate](http://stackoverflow.com/questions/9541025/how-to-copy-a-python-class) did you even try to search first? – danodonovan Feb 15 '13 at 16:07
  • [This answer](http://stackoverflow.com/questions/4199429/proper-way-to-deep-copy-with-copy-constructor-instead-of-object-clone) may also help you. It's better to use a copy constructor than clone. – Jess Feb 15 '13 at 16:08
  • It is a class instance. – Mokus Feb 18 '13 at 09:01
  • This will solve my problem:`newdcmd = copy.deepcopy( data ) newdcmd.settings = copy.deepcopy( data.settings )` – Mokus Feb 18 '13 at 09:02

1 Answers1

0

This works as documented I believe:

import copy

class Ex(object):
    clvar='foo'
    def __init__(self,i):
        self.i=i

    def __repr__(self):
        return 'clvar={}, self.i={}'.format(self.clvar,self.i)


ex1=Ex(1)
ex2=Ex(2)

excopy1=copy.deepcopy(ex1) 
excopy2=copy.deepcopy(ex2)     

print ex1,ex2   

print excopy1,excopy2

excopy1.i=22
excopy1.clvar='bar'

print ex1,excopy1

class Ex2(Ex):
    pass

ex2_2=Ex2(222)

print ex2_2    

Prints:

clvar=foo, self.i=1 clvar=foo, self.i=2
clvar=foo, self.i=1 clvar=foo, self.i=2
clvar=foo, self.i=1 clvar=bar, self.i=22
clvar=foo, self.i=222

The only way to 'copy' a class definition is through inheritance. You can copy instances with deepcopy but it is better form to write a copy method to take care of instance details.

the wolf
  • 34,510
  • 13
  • 53
  • 71