[Tutor] How to replace instances

Kent Johnson kent37 at tds.net
Thu Sep 25 12:58:56 CEST 2008

On Thu, Sep 25, 2008 at 4:24 AM, Steve Collins <emperor.ghaz at gmail.com> wrote:

> 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

'self' is just another parameter passed to the method, so this just
rebinds a local name.

This example doesn't seem to illustrate the situation you describe.
You can replace the 'y' attribute of a Z object by assigning to it.

One solution might be to make all your objects pickleable. Pickle
tracks object references and handles embedded references correctly.

> That doesn't raise any errors, but it also doesn't work:
>>>> a = X(10)
>>>> b = X(20)

Presumably this should be Z(10), Z(20) ?
>>>> print a.y
> 10
>>>> print b.y
> 20
>>>> b.replaceZ(a)
>>>> print b.y
> 20

If you want 'b' to refer to the same thing as 'a', just assign
b = a

I think you have some common misconceptions about the nature of
variables and assignment in Python. This may help:


More information about the Tutor mailing list