I would like to make a copy of a class instance in python. I tried copy.deepcopy
but I get the error message:
RuntimeError: Only Variables created explicitly by the user (graph leaves) support the deepcopy protocol at the moment
So suppose I have something like:
class C(object): def __init__(self,a,b, **kwargs): self.a=a self.b=b for x, v in kwargs.items(): setattr(self, x, v) c = C(4,5,'r'=2) c.a = 11 del c.b
And now I want to make an identical deep copy of c
, is there an easy way?
Yes, you can use copy. deepcopy . so just c2 = copy. deepcopy(c) then vars(c2) == {'a': 11, 'r': 2} and vars(c) == {'a': 11, 'r': 2} but the traceback your are reporting wouldn't be produced by the class definition you gave...
To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.
The deepcopy() function avoids these problems by: keeping a memo dictionary of objects already copied during the current copying pass; and. letting user-defined classes override the copying operation or the set of components copied.
Yes you can make a copy of class instance using deepcopy:
from copy import deepcopy c = C(4,5,'r'=2) d = deepcopy(c)
This creates the copy of class instance 'c' in 'd' .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With