Replace Whole Object Through Object Method

Stefan Schwarzer sschwarzer at sschwarzer.net
Sat Jul 1 05:42:43 EDT 2006


Hi Bruno :)

On 2006-06-27 10:30, Bruno Desthuilliers wrote:
> FWIW, a good part of the canonical design patterns are mostly workaround
> the lack of flexibility in languages like C++ and Java.

May be, but that doesn't exclude that some patterns are also
useful in Python. :-)

> The Strategy
> pattern's simplest Python implementation is to dynamically replace a
> method on a per-object basis. The State pattern's simplest
> implementation in Python is to dynamically change the class of an object.

It may be the "simplest" but it might not be the most "natural"
in terms of the problem domain.

At the Informationsdienst Wissenschaft ( http://idw-online.de )
we had a similar design problem. There, a person can have many
roles, like subscriber, journalist, public info officer etc. We
found it most natural to implement this with the actor/role
pattern, as I V described it.

> Of course, one of the canonical solutions to the OP's problem is to use
> composition/delegation. But doing it the canonical way would imply
> creating instances of the role objects and passing them the instance as
> param so they can access it's attributes. It works, but it creates a
> cyclic dependancy between the object and it's roles, so you would have
> to use weakrefs.

You don't have to, unless both classes have a __del__ method and
the garbage collector thus can't decide which to collect/delete
first.

> Dynamically creating new classes with the appropriate
> bases and assigning them to the object's __class__ attribute is another
> way to achieve the same result, and it's perfectly legal.

It might be "legal" but it also may be confusing. I would use the
design that makes the software easiest to maintain in the long
run. (If you don't know what the long run is, consider the
"medium run" and refactor later. :) )

> Now I do agree that it can become tricky to manage correctly wrt/ mro
> rules !-)

See? ;-) Software shouldn't be tricky (or only as tricky as
necessary). I value clarity over cleverness.

Stefan



More information about the Python-list mailing list