[Tutor] How to replace instances

Steve Collins emperor.ghaz at gmail.com
Thu Sep 25 10:24:31 CEST 2008


I've written a save/load function for a simple program using cPickle. Upon
saving, a master list, to which all instances are added in their __init__,
is pickled. when the program starts, if the user wishes to load, a variable
"load" is set to one, and the pickled list is loaded. All the classes either
A) initialize using the arguments provided or B) using the the attributes of
the instances in the un-pickled list. This seems a little clunky to me, but
it basically works.
However, some of the instances refer explicitly to other instances
instances. It's obvious why this causes problems. It occurred to me to
simply replace the instances with the ones in the un-pickled list, but I
don't know how.

I tried using the following approach:

class Z:
    def __init__(self,y):
        self.y = y
    def replaceZ (self,withWhat):
        self = withWhat


That doesn't raise any errors, but it also doesn't work:

>>> a = X(10)
>>> b = X(20)
>>> print a.y
10
>>> print b.y
20
>>> b.replaceZ(a)
>>> print b.y
20
>>> a
<__main__.X instance at 0x00D4AE18>
>>> b
<__main__.X instance at 0x00D54328>
>>>

Can anyone tell me how to achieve this?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080925/bb74e9f7/attachment.htm>


More information about the Tutor mailing list