getattr and setattr

Thomas Wouters thomas at xs4all.net
Thu Jul 6 09:53:20 EDT 2000


On Thu, Jul 06, 2000 at 01:58:45PM +0100, Dale Strickland-Clark wrote:

> I'm still trying to get to grips with object programming in Python and
> finding decent documentation unbelievably hard to track down.

Hm, I've never needed much more than the documentation on www.python.org:
the tutorial at first, then the language ref and the library ref ;)
The only parts lacking in there are Tkinter, and some modules which aren't
documented yet.

> I eagerly set about the tutorial but found it was  lacking in - well - just
> about every department.

The tutorial is more of an intro than a comprehensive educational track. Try
the Language Reference or the Library Reference. If you don't care for the
dull reference-style writing, try something like Learning Python, by
O'Reilly, or one of the other online tutorials available (sorry, no URLs ;P)

> I can't find any meat on __getattr__ and __setattr__.
> These two special object functions don't seem to be very well documented
> anywhere. (Please prove me wrong!)

The language reference, section 3.3, 'Special Method Names':
http://www.python.org/doc/ref/specialnames.html. To be more specific,
section 3.3.2, 'Customizing attribute access'. 

> I can see how to handle a special case in __getattr__ with something like:

> class wibble
>         def __getattr__(name):
>                 if name == 'fred':
>                         return 1
>                 else:
>                         # what?

> But what if it's not the special case(s). How do I return an arbitrary
> attribute? Do I do something like:

__getattr__ is only called if the attribute does *not* exist on the object.
The reason is fairly simple: if it was called for every lookup, __getattr__
itself could never be looked up !

If you decide, in your __getatr__, that an attribute shouldn't exist, you
should raise AttributeError. Don't do something like 'return 0' or you'll
confuse all kinds of internal mechanisms, like those that lookup special
method names ;)

__setattr__, however, is called for every attempt at storing a value in an
attribute, wether it exists or not. If you use __setattr__ and want to
alter an attribute, you shouldn't do the obvious ! If you assign from inside
__setattr__, __setattr__ is called again. Instead, you should modify
self.__dict__.

Section 3.3.2 explains all this, but in a bit less (and different ;) words.
-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list