Another two examples of using changing classes
Donn Cave
donn at u.washington.edu
Tue Aug 14 13:29:31 EDT 2001
Quoth Duncan Booth <duncan at NOSPAMrcp.co.uk>:
...
| And for those who have read the Gang of Four book, this is the State
| pattern which replaces the state variable and tests everywhere with a
| helper class for each state and forwarding each method to the current
| helper class. They also note that for languages that support it, another (I
| can't remember if they say better) way is to change the class of the object
| to reflect the state directly.
|
| I would think that the two most Pythonic ways to implement the State
| pattern would be to either have a base class with the common behaviour, and
| one derived class for each state, mutating the actual class to follow the
| current state, or simply have some helper classes with the state specific
| methods and update the instance's dictionary on state change.
|
| Somehow the C++ish alternative of forwarding all the methods doesn't appeal
| (even though in Python you could do the forwarding once in __getattr__),
| and the state variable really sucks.
I don't know, for me it's hard, even looking at the example, to
say whether it's awkward or just right, for its intended purpose -
whatever that is. It's also easy to imagine that a Python programmer
could do better, by common standards of Python programming, without
going to any kind of class mutation. I don't find class mutation to
be clearly Pythonic, in fact it seems diametrically opposite to the
clarity and explicitness of normal Python solutions.
I might be able picture a practical advantage to the state variable
if I thought about it. More generally, the instantiation of the
concrete states and the abstraction in separate instance objects.
For example, suppose some of the abstract functions are call and
response, and the response must use the same state that took the
call. If that state is a separate object, you can pass the state
as a parameter to get this effect, or you can look it up where
you don't have any procedural attachment to the concrete state.
If the state is embedded in the class, that's at best more
complicated to do, raises reentrancy questions etc.
Donn Cave, donn at u.washington.edu
More information about the Python-list
mailing list