1

As far as I know, copy.deepcopy copies objects which contained in target object.

But my code doesn't work in this situation.

import copy

class MyClass(object):
    list_value = [1, 2, 3, 4, 5]
    def __init__(self, name):
        self.name = name

a = MyClass('a')
b = copy.deepcopy(a)

a.list_value[0] = 10

print a.list_value
print b.list_value

The output was saying list_value of b instance is same with list_value of a.

[10, 2, 3, 4, 5]

[10, 2, 3, 4, 5]

What I expected was that list_value of only a changes.

Is there any thing I missed about deepcopy?

Community
  • 1
  • 1
JaeJun LEE
  • 1,234
  • 3
  • 11
  • 27

1 Answers1

3

list_value is a class attribute shared by all object instances of class MyClass. So even if you specify a.list_value[0], the list_value is the same for a and b. It's better to change your constructor to add it as an attribute for a specific object instance:

 def __init__(self, name):
      self.name = name
      self.list_value = [1, 2, 3, 4, 5]
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
  • Ahh... then, should I put only shared variables in a class field? – JaeJun LEE Apr 20 '15 at 08:59
  • Can you explain what you mean by "shared by all instances"? Also, provide links to the documentation about this phenomenon. – Ellis Percival Apr 20 '15 at 08:59
  • @Flyte, @Juniorcompressor I changed code as `JuniorCompressor` said, and there is no problem now. – JaeJun LEE Apr 20 '15 at 09:01
  • @Flyte: every single time something of class `MyClass` is made, it will have the **same** list `list_value`. A change made to `list_value` through any of the objects will change `list_value` for all of them. Here is a discussion http://stackoverflow.com/questions/11040438/class-variables-is-shared-across-all-instances-in-python – Joel Apr 20 '15 at 09:39
  • @Joel, According to the discussion, `list_value` of `MyClass` instance will work as shared attribute as long as there is no replacement operation about `list_value`? – JaeJun LEE Apr 20 '15 at 10:12