[Tutor] set/getattr and inheritance

Kirby Urner urnerk@qwest.net
Tue, 09 Oct 2001 15:54:49 -0700


I finally got that __getattribute__ provides behavior similar
to __getattr__, except it's *always* called, whether or not
the attribute is already in self.__dict__.

   >>> class C(object):
          def __init__(self,value):
	      self.value = value
	  def __getattribute__(self,arg):
	      return "Value: %s" % object.__getattribute__(self,arg)

   >>> o = C(3)
   >>> o.value
   'Value: 3'

The automatic triggering is implemented in the new universal
object, so you need to subclass object if you want this
behavior (otherwise __getattribute__ will just sit there
like an inert lump, not triggered by anything except an
explicit call).

Also, you don't want to invoke return self.__dict__[arg] to
return the attribute as part of the function'd definition,
as this just reinvokes __getattribute__ again in an
endlessly recursive tailspin.

Rather, call the base class version of __getattribute__,
as shown above.

This is all new with 2.2a4 -- becoming part of standard
Python of the future, but not currently accessible to
users of any final release.

I finally learned about this behavior from Guido's
PowerPoint slides available to PowerPointers at:
http://zpug.org/dc/ (from a presentation on Sept 26).

Kirby