[Tutor] detecting data member changes
alan.gauld at btinternet.com
Tue Apr 24 09:31:16 CEST 2007
"Luke Paireepinart" <rabidpoobear at gmail.com> wrote
> class wiimote(object):
> def __init__(self):
> self.leds = [0,0,0,0]
> def updateLEDs(self):
> do_stuff()#write correct output report to wiimote to toggle
> So basically what I want to do is that whenever the self.leds
> is changed, the updateLEDs method is called.
I'm not sure what your concern is here.
Since leds is an attribute of this class and therefore should only
be changed by a message to this class, then it should be easy
enough to ensure that each method that updates the leds calls
updateLED() when it makes a change
Or are you concerned about the possibility of someone directly
modifying leds from outside the class (naughty!). If its the latter
then you have the usual Python options:
- Make it single underscored and comment the fact that
mods should call update:LED() - The pythonic way of consenting
- Use the double underscore to make leds private
- Use setattr as you describe - I'm not clear why you need dictionary
- Use a property to make "direct access" via a method
- Make leds a class which uses setattr...
Or am I missing something else?
> I know I could use a __setattr__ but then I'd have to access the
> 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
> be off-putting to other people using my library.
Given that users of your class shouldn't be accessing leds directly
the format of the data should be of no interest to them. And a format
that discourages direct access would be a good thing - provided
your message interface makkes use of the class easy.
Author of the Learn to Program web site
More information about the Tutor