The below snippet has the same output no matter it is using the commented out ''copy.copy()'' or 'copy.deepcopy()''(Line 10). Why?
import copy
class A:
a = [1,2,3]
i = 3
obj = A()
#b = copy.copy(obj)
b = copy.deepcopy(obj)
b.a[0] = -1
b.i= 2
print obj.a
print b.a
print obj.i
print b.i
Both shallow copy and deep copy program output:
[-1, 2, 3]
[-1, 2, 3]
3
2
Isn't that deepcopy() will make a copy of obj so that b has its own copy of the list a? Why does changing b.a will affect the original object?
EDIT
Pynchia and user2357112 pointed out that part of this question is duplicate of the previous question. They are right about it. However, I noticed one weird behavior of python: Because the list a
is a class attribute, you make a deep copy of the object it does not copy the attribute. However, for i
, the integer value are different in b
and obj
. That means b
has its own copy of i
, even though i
is an class attribute.