Is it possible to copy an object in Python without copying a reference?
For example, if I define a class
class SomeClass: def __init__(self): self.value = 0
and then create an instance
someObject = SomeClass() someObject.value = 12
and I try to copy it to another instance:
anotherObject = someObject
and try to modify a property,
anotherObject.value = 10
the original property gets modified:
print someObject.value #prints 10
Is there any way to prevent this from happening? To clarify, I want the anotherObject.value
to contain 10
, but I want someObject.value
to still contain the original 12
. Is this possible in python?
Thanks in advance.
Assignment statements in Python do not create copies of objects, they only bind names to an object. For immutable objects, that usually doesn't make a difference. But for working with mutable objects or collections of mutable objects, you might be looking for a way to create “real copies” or “clones” of these objects.
b = a. copy() , this way it will work.
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Deep copy: copy. 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 problem is, with
anotherObject = someObject
you don't copy the object, but just add another reference to it. To copy an object, try this:
from copy import copy anotherObject = copy(someObject)
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