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

Peter Otten __peter__ at web.de
Sat Apr 22 03:52:52 EDT 2006


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