Pointers

Richard Jones Richard.Jones at fulcrum.com.au
Thu Mar 16 16:58:33 EST 2000


[smst]
> 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.

   Quite true, written incorrectly in haste - thanks for picking up the error.


> (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.

   Also quite true: this one comes from my not having actually programmed in 
Python for _far_ too long now :(


        Richard






More information about the Python-list mailing list