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

Sandra-24 sandravandale at yahoo.com
Sat Apr 22 16:02:04 EDT 2006


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?

Thanks,
-Sandra

Peter Otten wrote:
> Sandra-24 wrote:
>
> > Can you create an instance of a subclass using an existing instance of
> > the base class?
> >
> > Such things would be impossible in some languages or very difficult in
> > others. I wonder if this can be done in python, without copying the
> > base class instance, which in my case is a very expensive object.
>
> You can change the class of an instance by assigning to the __class__
> attribute. The new class doesn't even need to be a subclass of the old:
>
> >>> class A(object):
> ...     def __init__(self, name):
> ...             self.name = name
> ...     def show(self): print self.name
> ...
> >>> a = A("alpha")
> >>> a.show()
> alpha
> >>> class B(object):
> ...     def show(self): print self.name.upper()
> ...
> >>> a.__class__ = B
> >>> a.show()
> ALPHA
> 
> Peter




More information about the Python-list mailing list