Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: deepcopy does not work on user-defined classes?

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)]
like image 466
Elrond1337 Avatar asked Aug 21 '13 17:08

Elrond1337


People also ask

Can you copy an instance of a class in Python?

Yes, you can use copy. deepcopy . so just c2 = copy.

What is Deepcopy () in Python?

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.

How do you distinguish between copy copy () and copy Deepcopy ()?

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.

What is the difference between shallow copy and Deepcopy in Python?

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.


1 Answers

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)]
like image 99
Jon Clements Avatar answered Nov 15 '22 19:11

Jon Clements