Intercept methods/raise exception
Gordon McMillan
gmcm at hypernet.com
Thu Jul 20 19:55:14 EDT 2000
Thomas Weholt wrote:
>Is there a way to define a method in a class that is called each time
>every other method is called in that class, and based on a attribute,
>raise an exception or let the method-class go thru?
Not with a method. Use a proxy:
class Proxy:
def __init__(self, obj):
self.__dict__['_obj'] = obj # avoid the __setattr__ hook
def __getattr__(self, nm):
attr = getattr(self._obj, nm, None)
if attr:
# do what you like
return attr
raise AttributeError, "%s not found" % nm # vital
def __setattr__(self, nm, val):
# do what you like and maybe
setattr(self._obj, nm, val)
Now just wrap your object in the proxy.
-Gordon
More information about the Python-list
mailing list