Intercept methods/raise exception

Thomas Weholt thomas at cintra.no
Fri Jul 21 05:07:39 EDT 2000


On 20 Jul 2000 23:55:14 GMT, gmcm at hypernet.com (Gordon McMillan)
wrote:

>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


Ok, it seems to work, allthough only if I access methods. Accessing
simple values like ints and strings directly only traps that value,
not the attribute name. 

class foo:
	def __init__(self):
		self.poofoo = 2
	def foobar(self):
		return 1

a = foo()
x = Proxy(a)
x.foobar()

will trap foobar as the attr. 

x.poofoo
will only trap the value stored in that attribute.

How can I trap the attribute *name* too?

And, most importantly, how can I make my objects behave like the ones
used thru a proxy, *without* putting them into one? is it possible? I
mean, I just want to avoid have to declare one instance, and then
stuff it into another new instance. Can it be done in one big swoop?

Anyway, where can I read up on stuff like this? Proxy, nifty object
handling. Any hints?

Thanks for any help so far. It helped me alot.

Thomas




More information about the Python-list mailing list