how to copy a Python object
Schüle Daniel
uval at rz.uni-karlsruhe.de
Tue Feb 7 09:05:02 EST 2006
mitsura at skynet.be wrote:
> Already thanks for the reply,
>
> but how to write your own copy operator? Won't you always be passing
> referrences to new_obj?
for example this would work
>>> class X(object):
... def __init__(self,lst):
... self.lst = lst
... def copy(self):
... return X(self.lst[:])
... def __str__(self):
... return "lst has id %i" % id(self.lst)
...
>>> x=X([1,2,3])
>>> y=x.copy()
>>> print x
lst has id 1078097132
>>> print y
lst has id 1078097228
but I don't like that in this case self.lst must be passed
through __init__
I can think of another variant
>>> class Y(object):
... def fill(self):
... self.lst = [randint(i*10,(i+1)*10) for i in xrange(5)]
... def __repr__(self):
... return "lst has id = %i" % id(self.lst)
... def copy(self):
... ret = Y()
... ret.lst = self.lst[:]
... return ret
...
>>> from random import randint
>>> y=Y()
>>> y.fill()
>>> y
lst has id = 1078097452
>>> print y
lst has id = 1078097452
>>> x=y.copy()
>>> x
lst has id = 1078097004
... anyone?
are there better approaches?
Regards, Daniel
More information about the Python-list
mailing list