Catching all methods before they execute
Michael Hoffman
cam.ac.uk at mh391.invalid
Mon Mar 7 14:34:35 EST 2005
jamesthiele.usenet at gmail.com wrote:
> l = Undoable(list)
> l = [1, 2, 3]
You just rebound l, so it no longer refers to an Undoable, it
refers to a list. This design won't work, you need something
more like:
l = Undoable([1, 2, 3])
There were a few other pitfalls in your design... Here,
try something like this instead:
class SurrogateNotInitedError(exceptions.AttributeError):
pass
class Surrogate(object):
"""
the data is stored in _data
>>> list1 = [0, 1, 2, 3]
>>> list2 = [4, 5, 6, 7]
>>> surrogate = Surrogate(list1)
>>> surrogate.reverse()
>>> list1
[3, 2, 1, 0]
>>> surrogate._data = list2
>>> surrogate.append(8)
>>> list2
[4, 5, 6, 7, 8]
"""
def __init__(self, data):
self._data = data
def __getattr__(self, name):
if name == "_data":
raise SurrogateNotInitedError, name
else:
try:
return getattr(self._data, name)
except SurrogateNotInitedError:
raise SurrogateNotInitedError, name
You can modify this to make an UndoableSurrogate with appropriate saving
of state. Note the use of __getattr__ instead of __getattribute__. The
latter is not needed since there are not any attributes defined on
Surrogate instead.
--
Michael Hoffman
More information about the Python-list
mailing list