Could an object delegate itself into another?

Bernhard Herzog herzog at online.de
Fri Oct 22 07:16:12 EDT 1999


François Pinard <pinard at IRO.UMontreal.CA> writes:

> "Fred L. Drake, Jr." <fdrake at acm.org> écrit:
> 
> > François Pinard <pinard at iro.umontreal.ca> writes:
> >  > But yet, I wonder.  Could an object really delegates itself into
> >  > another?  For example, is there some way by which a newly created
> >  > object could soon check, probably within __init__, if a similar copy
> >  > has already been registered?
> 
> > 	>>> class C: pass
> >         ...
> >         >>> c1 = C()
> >         >>> c2 = C()
> >         >>> c2.__dict__ = c1.__dict__
> >         >>> c1.foo = "bar"
> >         >>> c2.foo
> >         'bar'
> 
> Quite interesting.  So you are saying that the implementation of an instance
> is fully held in its __dict__?  That would be simple enough, then...

The only thing not held in __dict__ is its class and its id.

> >   Not to be used in real code!

I've always wondered what you might use this for. The only thing I came
up with is that you can use it swap two objects *in place*, which can be
handy if you can't change the objects that refer to them. So with code
like this:

	c.__dict__, d.__dict__ = d.__dict__, c.__dict__
	c.__class__, d.__class__ = d.__class__, c.__class__

you get them to kind of swap their bodies, but since they retain their
identity their finger prints stay the same, so to speak.

> Yet if you are right, this is exactly the functionality I was looking
> for. What else, then? I do agree that `self.__dict__ = some.__dict__'
> might look tinily odd within an `__init__' function, at least until I
> get used to it :-)

One problem with this is that you still have two different instances.
That they share their instance variables can lead to all kinds of
problems. For instance, if your class has a __del__ method that modifies
the instance variables you'll get problems because the two objects are
collected at different times and the second call to __del__ will likely
fail. Furthermore, after the first __del__ call your object might be in
an undefined state.

The sane approach is to use a factory function that maintains a cache of
instances as suggested by other posters.



-- 
Bernhard Herzog	  | Sketch, a drawing program for Unix
herzog at online.de  | http://www.online.de/home/sketch/




More information about the Python-list mailing list