Changing class membership

matthias.oberlaender at daimlerchrysler.com matthias.oberlaender at daimlerchrysler.com
Fri Sep 29 05:30:46 EDT 2000


In <8qt1ci$ecj$1 at desig-bs01-s04.adtranzsig.de> "Dirk-Ulrich Heise" wrote:
> How do i most elegantly let an object switch its class
> membership? My problem is, i have a sort of proxy object
> with a name. When this proxy object gets a certain request
> (especially, for a text it represents), it can't answer this
> request because it doesn't have the info. But it knows
> where to look on the harddisk, so it will load this text,
> magically become a "real object" (no more a proxy, but
> now a full-fitted object that has all its info), and answer the
> request.
> 
> On later requests, it will have forgotten about it's infant
> proxy status but simply tell everybody the info it has now.
> 
> I guess that's called "switching modes". Hmm. Maybe,
> for now i'll simply switch with a bool member. Anyway,
> somebody used mode switching out there? Pros?
> Cons? Advice for this design decision?
> 
> 
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. 

I don't claim to have a very deep understanding of Pythons implementation 
architecture yet. So maybe I missed something. But for me it works. I have 
"lazy objects" (your "proxy" objects) which expand to their real beings on 
the first access to any of their expected attributes. This can be easily 
achieved by writing an appropriate   __getattr__ method for the the lazy 
class. 

  def __getattr__(self, name):
    # The first access to any attribute or method will transmogrify an
    # instance of class 'Xlazy' into an instance of class 'Xreal'
    newself = Xreal ()
    transmogrify(self, newself)
    return __builtin__.getattr(self, name)

--
=====================================================================
Matthias Oberlaender, DaimlerChrysler AG, Research Center Ulm
FT3/AB (Information Technology / Image Understanding)
Wilhelm-Runge-Str. 11,  P.O. Box 2360,  89013 Ulm, Germany
Phone: +49 731 505 2354       Fax: +49 731 505 4113
Email: matthias.oberlaender at daimlerchrysler.com
=====================================================================




More information about the Python-list mailing list