In the following example I would expect deepcopy to create a copy of field and not just copy the reference. What happens here and is there an easy way around it?
from copy import deepcopy
class Test:
field = [(1,2)]
t1 = Test()
t2 = deepcopy(t1)
t2.field[0]=(5,10)
print t1.field # [(1,2)] expected but [(5,10)] obtained
print t2.field # [(5,10)] expected
Output:
[(5, 10)]
[(5, 10)]
Yes, you can use copy. deepcopy . so just c2 = copy.
A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements. Let's continue with example 2. However, we are going to create deep copy using deepcopy() function present in copy module.
copy() create reference to original object. If you change copied object - you change the original object. . deepcopy() creates new object and does real copying of original object to new one. Changing new deepcopied object doesn't affect original object.
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 copying (by default) only applies to instance level attributes - not class level - It doesn't make much sense that there's more than one unique class.attribute
...
Change your code to:
class Test:
def __init__(self):
self.field = [(1,2)]
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