Downcast (I know it sounds silly, but ...)

Terry Reedy tjreedy at udel.edu
Thu Jan 2 15:53:29 EST 2003


"Rocco Rossi" <rockrossi69 at libero.it> wrote in message
news:cX0R9.72667$Ou4.2409063 at twister2.libero.it...
> I was wondering if it is possible in Python to do something
analogous to
> downcasting in a statically typed language like C++. I mean is it
possible
> to take an instance of a base class and magically transform it into
an
> instance of some derived class eventually fixing things (like the
missing
> attribute data)?

Maybe.  If you can modify __class__ to the derived class, yes.  If you
cannot, no.
You can only do so with new-style classes if the layouts are
'compatible' -- but I do not know the rules for what is.

With 2.2.1:
>>> class C: pass
...
>>> class CC(C): pass
...
>>> c = C()
>>> c.__class__
<class __main__.C at 0x00794ED0>
>>> c.__class__ = CC
>>> c.__class__
<class __main__.CC at 0x007940A0>

>>> class N(object): pass
...
>>> n = object()
>>> n.__class__
<type 'object'>
>>> n.__class__ = N
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __class__ assignment: 'N' object layout differs from
'object'
>>> class NN(N): pass
...
>>> n=N()
>>> n.__class__
<class '__main__.N'>
>>> N.__class__ = NN
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __class__ assignment: 'NN' object layout differs from
'type'






More information about the Python-list mailing list