Entry
How do I copy one object into another without having them refer to each other?
May 12th, 2000 07:29
unknown unknown, Emile van Sebille, Thomas Thiele
You could create a separate instance, or provide a copy
function as part of the class.
>>> a = A('bragi')
>>> b = A('')
>>> b.name = a.name
>>> b.name
'bragi'
>>> a.name = 'stini'
>>> b.name
'bragi'
>>>
>>> class A:
def __init__(self,name):
self.name = name
def copy(self):
retval = A(self.name)
# other copy functions
return retval
>>> a = A('bragi')
>>> b = a.copy()
>>> b.name
'bragi'
>>> a.name = 'stini'
>>> b.name
'bragi'
>>>
Or, you could use copy.copy and copy.deepcopy.
>>> class X:
... def __init__(self):
... self.a = 5
...
>>> x = X()
>>> list = [x]
>>> cl1 = copy.copy(list)
>>> cl2 = copy.deepcopy(list)
>>> list[0].a = 6
>>> list[0].a
6
>>> cl1[0].a
6
>>> cl2[0].a
5