Copy constructors

Christian Tanzer tanzer at swing.co.at
Mon Aug 13 07:41:43 CEST 2001


Guido van Rossum <guido at python.org> wrote:

> Roeland Rengelink <r.b.rigilink at chello.nl> writes:
> 
> > One idiom where I use __class__ assignment is the following
> > 
> > class State1:
> >     def do_something(self):
> >         ...do something...
> >     def change_state(self):
> >         self.__class__ = State2
> > class State2:
> >     def do_something(self):
> >         ...do something else...
> >     def change_state(self):
> >         self.__class__ = State1
> 
> But you can easily do this differently -- e.g. you could do a method
> assignment, or you could represent the state by an object.

For some definition of easy...

If the change affects several methods instead of one you could still
use method assignments but that's not easy compared to a simple
__class__ assignment.

A proxy object is a clean solution but introduces additional
complexity. 

Disclaimer: I currently don't use __class__ assignment (except once in
very experimental code). Yet I know several design patterns where it
provides a convenient solution -- 

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list