how to copy a Python object

Alex Martelli aleaxit at yahoo.com
Wed Feb 8 01:12:52 EST 2006


Schüle Daniel <uval at rz.uni-karlsruhe.de> wrote:
   ...
>  >>> 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)
   ...
> ... anyone?
> are there better approaches?

def __getstate__(self): return self.lst

def __setstate__(self, L): self.lst = L

and copy an instance x of X with copy.copy(x) [[after import copy, of
course]].  This will also support pickling &c.  getstate/setstate are
generally the best approach.  An equally good alternative here, omit
setstate and just:

def __getstate__(self): return dict(lst=self.lst)


Alex




More information about the Python-list mailing list