Python Patterns (was: Re: How can I make an existing object read-only?)
Irmen de Jong
irmen at -nospam-remove-this-xs4all.nl
Tue Oct 5 15:00:57 EDT 2004
Alex Martelli wrote:
> ...or implement it by changing the object's *class*...:
>
> class RO_class(TrueClass):
> def makeReadWrite(self): self.__class__ = TrueClass
> def __setattr__(self, n, v=''): raise AttributeError, n
> __delattr__ = __setattr__
>
> def makeReadOnly(obj): obj.__class__ = RO_class
>
> This is a very Pythonic approach to dealing with an object that exists
> in two 'states', each rather persistent and with different behavior; it
> is better performing and neater than using an obj._state and having 'if
> self._state: ... else: ...' statements strewn around.
I think this the kind of solution I think I was searching for!
And should have been able to think up myself.
I really should dust off my old GOF Desing Patterns book,
because your code made me remember the "state" pattern right away :-)
There should be a Python version of that book... I think that
the patterns in it are very easily expressed in Python, and
that Python allows for many other interesting patters ('Borg', to
name one).
This "state" pattern needs a clumsy internal state object in C++
but in Python we can just change the object's class directly,
which is a much more direct implementation of what the pattern
tries to achieve :-)
Thanks Alex
--Irmen de Jong.
More information about the Python-list
mailing list