Changing the class of an instance

Dinu C. Gherman gherman at darwin.in-berlin.de
Thu Jul 13 10:42:30 EDT 2000


Paul Prescod wrote:
> 
> 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.

This is a typical case for using one of the following 
design patterns: Abstract Factory, Builder, Factory 
Method (see "Design Patterns" by Gamma et al. for de-
tails).

There is really no need for turning OO concepts upside-
down only because the specification of a particular 
language allows for doing it (unless there is no other 
proper way to do it...).

Regards,

Dinu

-- 
Dinu C. Gherman
................................................................
"The only possible values [for quality] are 'excellent' and 'in-
sanely excellent', depending on whether lives are at stake or 
not. Otherwise you don't enjoy your work, you don't work well, 
and the project goes down the drain." 
                    (Kent Beck, "Extreme Programming Explained")



More information about the Python-list mailing list