创建一个新的obj与deepcopy,但新的obj共享变量与旧的obj [英] Create a new obj with deepcopy but new obj share variable with the old obj

查看:286
本文介绍了创建一个新的obj与deepcopy,但新的obj共享变量与旧的obj的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用pygraph模块处理一些类,当我使用add_node()方法,它总是出现'节点xxx已经在图形'。所以我尝试使用deepcopy()创建一个新的实例,并有一些问题:

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)

它显示:

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

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

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

但是如果我向列表a2中添加一些新项目,a3也会改变

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 ??

推荐答案

_storage 是一个类变量。 deepcopy 不会创建整个类的新副本,因此副本仍然会共享相同的类变量。你想要的是一个实例变量:

_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 = []

这篇关于创建一个新的obj与deepcopy,但新的obj共享变量与旧的obj的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆