Can you create an instance of a subclass with an existing instance of the base class?

Peter Otten __peter__ at web.de
Sun Apr 23 02:31:39 EDT 2006


Sandra-24 wrote:

> Now that is a clever little trick. I never would have guessed you can
> assign to __class__, Python always surprises me in it's sheer
> flexibility.
> 
> In this case it doesn't work.
> 
> TypeError: __class__ assignment: only for heap types
> 
> I suspect that's because this object begins its life in C code.
> 
> The technique of using the __class__.__subclasses__ also fails:
> 
> TypeError: cannot create 'B' instances
> 
> This seems more complex than I thought. Can one do this for an object
> that beings it's life in C?

The restriction originates in the metaclass. Perhaps you can use a
customized metaclass that allows subclass assignment, but I don't know
enough about Python's internals to tell you how/whether that is possible.

An alternative might be that you always start out with a subclass coded in
Python:

>>> abc = tuple("abc")
>>> abc.__class__ = tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __class__ assignment: only for heap types


>>> class Tuple(tuple): pass
...
>>> class Subclass(Tuple):
...     first = property(lambda self: self[0])
...
>>> abc = Tuple("abc")
>>> abc.__class__ = Subclass
>>> abc.first
'a'

In the example a Tuple should be able to do everything a tuple can do;
because Tuple is coded in Python you can also change the __class__.

Peter






More information about the Python-list mailing list