setattr getattr confusion

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Dec 8 12:21:38 EST 2007


Donn Ingle a écrit :
>>class Key(object):
>>def __init__self):
>>self.__dict__['props'] = KeyProps()
> 
> Okay - that's weird.

No, that's coherent. The default behavior (I mean, when there's no 
descriptor involved etc) of __setattr__ is to store attributes in 
instance.__dict__. So as long a you override __setattr__, you have to 
take care of this by yourself.

> Is there another way to spin this?
> 
>>def __setattr__(self,var,val):
>>setattr(self.props,var,val)
> 
> Perhaps by changing this one?

If you know by advance which names should live in your object and/or 
which should belong to the KeyProps instance, then you can check and 
dispatch, ie:


class Key(object):
   # names that must not be delegated to instance.props
   _mynames = ['props', 'foo', 'bar']

   def __setattr__(self, name, value):
     if name in self._mynames:
       object.__setattr__(self, name, value)
     else:
       setattr(self.props, name, value)




More information about the Python-list mailing list