Changing the class of an instance

Paul Prescod paul at prescod.net
Thu Jul 13 06:50:29 EDT 2000


Huaiyu Zhu wrote:
> 
> ...
>
> I also find I need to do this a lot of time.  For example, when you read
> something from a file, you want to return an object of a specific class
> based on the content.  The easiest way to do it appears to be
> 
> class General:
>    __init__(self, data):
>        self.data = data
>        if data is something:
>            self.__class__ = Special1
>        else:
>            self.__class__ = Special2
> 
> class Special1(General): pass
> 
> class Special2(General): pass

YOur code would work just as well if Special1 and Special2 were not
related to General. In fact, it would work if you separated out that
init function into something that reads the data and creates an
appropriate class instance based on the data.

-- 
 Paul Prescod - Not encumbered by corporate consensus
Simplicity does not precede complexity, but follows it. 
	- http://www.cs.yale.edu/~perlis-alan/quotes.html




More information about the Python-list mailing list