Search code examples
pythondeep-copy

How can I clone a class?


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?


Solution

  • 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.