[Tutor] question on getattr..

Justin Sheehy dworkin@ccs.neu.edu
12 May 2000 18:25:24 -0400


Kevin Liang <kevin@vcn.bc.ca> writes:

> class wrapper:
> 	def __init__(self,object):
> 		self.wrapped = object
> 	def __getattr__(self, attrname):
> 		print 'Trace:', attrname
> 		return getattr(self.wrapped, attrname)
> 
>   I know you need the last line to acutally use built-in functions
>   for lists, > dictionaries, etc.. (e.g. append something), but what
>   does it mean ? Why is a return needed ?  I keep thinking its
>   supposed to print something..

I'm not sure what you mean by needing that line to use builtin
functions, etc.  getattr() is just a way to dynamically access any
member of an object.  

This:

attrname = 'eggs'
x = getattr(self.wrapped, attrname) 

is basically equivalent to:

x = self.wrapped.eggs

If that doesn't make it clear, then reading the standard Python
documentation on the builtin function getattr() might be useful.

This class is presumably used by whoever wrote it for debugging
purposes.  It simply contains an object and prints to stdout when
instance members are referenced through it.  It uses the special class 
method __getattr__() to achieve this.  Handy stuff that's hard to do
in many other languages.

For instance:

>>> class X:
...  pass
... 
>>> x = X()
>>> x.spam = 1
>>> y = wrapper(x)
>>> y.spam
Trace: spam
1

The last line was returned by the __getattr__(), the one before it was 
emitted by the print statement.

-Justin