[Tutor] detecting data member changes
Kent Johnson
kent37 at tds.net
Tue Apr 24 12:30:18 CEST 2007
Luke Paireepinart wrote:
> Supposing I have a class like this:
>
> 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 LEDs.
>
> So basically what I want to do is that whenever the self.leds variable
> is changed, the updateLEDs method is called.
> ( I can't call it constantly in a loop because 1) the wii remote freaks
> out, and 2) that seems pretty ineffiicent.)
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
I renamed _updateLEDs because it doesn't seem like this should be part
of the public interface.
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()
Kent
More information about the Tutor
mailing list