Changing class membership

Glyph Lefkowitz glyph at no.spam
Fri Sep 29 15:53:33 EDT 2000


matthias.oberlaender at daimlerchrysler.com writes:

> In <8qt1ci$ecj$1 at desig-bs01-s04.adtranzsig.de> "Dirk-Ulrich Heise" wrote:

> I believed for years that "object evolution" is a useful and elegant concept. 
> Only a month ago I started learning Python and soon realized how easy it 
> would be to implement. That's my current solution:
> 
> def transmogrify(x, y):
> # Exchanges the properties of instances x and y.
> # The identity of x and y remain the same. But their 
> # class membership and all their attributes get exchanged. 
>   h = x.__dict__
>   x.__dict__ = y.__dict__
>   y.__dict__ = h
>   h = x.__class__
>   x.__class__ = y.__class__
>   y.__class__ = h
> 
> Key is to exchange the objects' dictionaries also, not only class membership. 
That's a lot of lines of code :-).  How about

def transmogrify(x, y):
  x.__dict__, x.__class__ = y.__dict__, y.__class__

-- 
Glyph Lefkowitz
Professional -- Software Engineer,  Origin Systems
Amateur      -- Computer Scientist, Twisted Matrix Enterprises
(My opinions are my own and do not reflect in any way on the policies
or practices of my employer, etcetera etcetera.)



More information about the Python-list mailing list