[Tutor] detecting data member changes

Kent Johnson kent37 at tds.net
Tue Apr 24 16:54:07 CEST 2007


Luke Paireepinart wrote:

>>> I know I could use a __setattr__ but then I'd have to access the leds 
>>> using a dictionary with an 'LED' key mapped to the status array.
>>> It's not necessarily a bad thing for my own use, but it seems like 
>>> it'd be off-putting to other people using my library.
>>
>> I don't understand this part. It seems to me this would work:
>> def __setattr__(self, name, value):
>>   object.__setattr__(self, name, value)
>>   if name == 'leds':
>>     self._updateLEDs()
> What I meant was that it'd require people to access the variable via
> classinstance['leds']
> instead of
> classinstance.leds
> which is what I was aiming for.
> I apologize, I should've waited till the morning to e-mail so I could be 
> more coherent.

No, the above code should work with classinstance.leds. Maybe you are 
confusing __setattr__ - which affects attributes like .leds - with 
__setitem__ which is used for classinstance['leds']

> 
> Is this properties method acceptable Python form or is it more proper to 
> have modifying member functions like Alan said?

Alan and I don't always agree on questions like this. I don't take such 
a hard position about direct attribute access. IMO using a property is 
more Pythonic than making an explicit method. But I think one of the 
nice things about Python is you don't have to write explicit getters and 
setters; you can use plain attribute access to get at plain data, then 
if you need to add some behaviour just change the attribute to a property.

> Or is it really up to me on how I want to implement it?

Of course, it's your code, right?

Kent


More information about the Tutor mailing list