converting base class instance to derived class instance

François Pinard pinard at iro.umontreal.ca
Mon Feb 9 10:07:17 EST 2004


[John Roth]

> If you want to do a little bit of deep magic, a factory function can
> create an instance by calling object(), plug in whatever attributes
> it wants and then change the __class__ attribute to whatever class it
> wants before it returns the newly minted instance. It doesn't have
> to go near anything that resembles a constructor (other than calling
> object() to get a new instance, of course.)

Hello, John, and gang! :-)

How one does that?  I'm merely curious.  Using Python 2.3.3, the result
of `object()' does not have a `__dict__', and seemingly may not be given
a `__dict__' either.  See:


Python 2.3.3 (#1, Jan 24 2004, 09:01:30) 
[GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
from __future__ import division
>>> from __future__ import division
>>> o = object()
>>> o.__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'object' object has no attribute '__dict__'
>>> o.__dict__ = {}
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'object' object has no attribute '__dict__'
>>> class C(object): pass
... 
>>> o.__class__ = C
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __class__ assignment: only for heap types
>>> 


By the way, what is a "heap type"?

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list