Pointers

smst smstNOsmSPAM at bigfoot.com.invalid
Thu Mar 16 06:02:29 EST 2000


In article <200003160037.LAA28211 at envy.fulcrum.com.au>,
Richard.Jones at fulcrum.com.au (Richard Jones) wrote:
>
>>>> d={'A':0,'B':0}
>>>> class A:
>....  def __init__(self, d):
>....   self.d = d
>....  def __getattr__(self, attr):
>....   if attr == 'a':
>....    return d['A']
>....   return self.__dict__[attr]
>....
I don't want to sound picky, but just in case Curtis uses that
class he may find a couple of problems:

(1) returning d['A'] returns a value in some global object d,
which mat or may not exist (although it did in your example).  A
value from self.d is probably better.

(2) __getattr__ doesn't necessarily work as you expect -- it's
only called if an attribute is not found on an object, and so
trying to return self.__dict__[attr] is unnecessary -- the key
won't exist (and in fact will raise a KeyError, confusingly).
I'd recommend  'raise AttributeError, attr'  instead.

> So that in this example, we are intercepting the accessing of
> the attributes in the classes 'A' and 'B' so they return the
> values from the dictionary 'd' instead of any attribute 'a' or
> 'b' they might have.
>
As I mentioned above, this isn't strictly true -- if the
instance does have an attribute 'a' or 'b', it will be retrieved
and __getattr__ won't be called.


> A more complete solution that intercepts the setting of the
> attributes 'a' or 'b' is left as an exercise for the reader.
>
Indeed, this is what you'd need to do to get the behaviour above
(returning self.d['a'] instead of self.a) -- use __setattr__ to
store attributes in some special dictionary (self._attrs or
such) so that __getattr__ will have to be called.  See the
Python Language Reference, section 3.3.2 .

Cheers,
Steve Tregidgo
http://www.businesscollaborator.com

* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!




More information about the Python-list mailing list