Changing the class of an instance

Bernhard Herzog herzog at online.de
Wed Jul 12 19:02:15 EDT 2000


hzhu at knowledgetrack.com (Huaiyu Zhu) writes:

> 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

In this case I think a factory function would be much cleaner:

def instantiate(data):
	if data is something:
		return Special1(data)
	else:
		return Special2(data)

Putting knowledge about what derived classes exist into the base class
is the wrong approach, IMO. You obviously have to have knowledge about
the derived classes somewhere in the code, and the right place for that
is a factory function or something similar outside of the class
hierarchy.


-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list