0

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.

Community
  • 1
  • 1
Junji Zhi
  • 1,382
  • 1
  • 14
  • 22
  • it's a long subject. `a` is a `class attribute`, not an `instance attribute` – Pynchia Jan 26 '16 at 20:42
  • You are right. When the list is a class attribute, you make a deep copy of the object it does not copy the attribute. However, I noticed i, the integer value gets changed. That means b has its own copy of i, even though it is an instance attribute. – Junji Zhi Jan 26 '16 at 20:51
  • I think you meant to say `even though it is a class attribute`. The assignment `b.i = 2` creates an instance attribute. See if [this answer](http://stackoverflow.com/questions/29702149/unable-to-access-value-of-global-variable-in-functions-other-than-it-is-initiali/29703345#29703345) of mine helps – Pynchia Jan 26 '16 at 21:02
  • Thanks. So `b.i = 2` creates an instance attribute even though there exist a class attribute with the same name `i`? This python grammar puzzles me. – Junji Zhi Jan 26 '16 at 21:28
  • Yes, correct. The assignment defines in which namespace the name lives. On the other hand, when you reference it (i.e. use a name, e.g. in an expression), python looks for it in the namespace of the instance and if it cannot find it it looks for it in the namespace of the class. Note: that is done for any name, be it variables, methods, etc. – Pynchia Jan 26 '16 at 21:33

0 Answers0