Search code examples
pythoncopyshared-memorydeep-copyclass-variables

Create a new obj with deepcopy but new obj share variable with the old obj


I am dealing with some classes using pygraph module and when I use add_node() method, it always comes out 'node xxx already in graph'. So I try to use deepcopy() to create a new instance and have some problem with it:

class test:
   _storage = []
   def add_item(self,item):
       self._storage.append(item)

   def pop_item(self,item):
       return self._storage.pop()

   def __repr__(self):
       return '%s' %self._storage[:]

if __name__ == '__main__':
   a1 = test()
   a1.add_item(3)
   a1.add_item(4)
   from copy import copy,deepcopy
   a2 = copy(a1)
   a3 = deepcopy(a2)

it shows:

In[28]: a1
Out[28]: [3, 4]

In[29]: a2
Out[29]: [3, 4]

In[30]: a3
Out[30]: [3, 4]

but if I add some new item into the list a2, a3 changes too

In[31]: a1.add_item(440)

In[32]: a2
Out[32]: [3, 4, 440]

In[33]: a3
Out[33]: [3, 4, 440]

So how can I just copy some instance and the variables of it are independent from variables in the old instance ??


Solution

  • _storage is a class variable. deepcopy won't make a new copy of the whole class, so copies will still share the same class variables. What you want is an instance variable:

    def __init__(self):
        self._storage = []