[Tutor] detecting data member changes

Luke Paireepinart rabidpoobear at gmail.com
Tue Apr 24 16:27:25 CEST 2007

> Make leds a property:
> class wiimote(object):
>     def __init__(self):
>         self._leds = [0, 0, 0, 0]
>     def _set_leds(self, leds):
>         self._leds = leds
>         self._updateLEDs()
>     def _get_leds(self):
>         return self._leds
>     leds = property(_get_leds, _set_leds)
>     def _updateLEDs(self):
>         print self._leds
> w = wiimote()
> print w.leds
> w.leds = [1, 2, 3, 4]
> print w.leds
Wow, that's cool.  I need to read more about properties.
> I renamed _updateLEDs because it doesn't seem like this should be part 
> of the public interface.
Yeah, it was prepended with an underscore in my code, I forgot to put it 
when I simplified the code here.  *embarrassed*
> If you don't like having _set_leds and _get_leds in the namespace of 
> wiimote, use one of the recipes here:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
>> 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
instead of
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.

Is this properties method acceptable Python form or is it more proper to 
have modifying member functions like Alan said?
Or is it really up to me on how I want to implement it?
> Kent

More information about the Tutor mailing list