[Tutor] detecting data member changes

Alan Gauld alan.gauld at btinternet.com
Tue Apr 24 19:14:19 CEST 2007


"Luke Paireepinart" <rabidpoobear at gmail.com> wrote

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

Properties is fine and was one of the options that I suggested.

However I didn't mean you should have modifying member
functions in the sense of set/get merthods - I actually hate
those generally!

What I meant is that, whatever a wiimote is, it should be offering
up a behaviour oriented inteface that, as a side-effect, changes
the internal leds attribute. OOP is all about abstracting some
higher level object into a set of behaviours. The attributes of an
object should only really be there to support those higher
behaviours. So what is it that a wiimote does? And how
does that behaviour affect the leds? That is the set of methods
to build. (Since I've never heard of a wiimote I have no idea
what the abstract behaviour might be!)

For example, if I build a lamp object I might have an
_isLit boolean attribute internally.
Now I could write a method to set the _isLit attribute to
True or False

lamp = Lamp()
lamp.setIsLit(True)
lamp.setIsLit(False)

And superficioally it looks like OK code that does the job.

But that's not how people intuitively think of lamps.
They light them or turn them off. So the code is better if
the Lamp class provides on/off methods that control the
_isLit attribute:

lamp = Lamp()
lamp.on()
lamp.off()

And its easier to use so there no temptaiuon to mess with the
attribute directly and I can change the _isLit type from Boolean
to a number or a string or whatever I want and the client code
is unaffected.

Thats what I mean about providing a message interface that negates
the need for users of the class to know or care about the leds 
attribute.
If you make it intuitive and easy to use the class via messages then
there is no incentive to go messing with the internals.

However if you do need direct access to a data attribute then
direct access is usually OK. If the class is primarily there to
store some bit oif data (but that should be the exception in
OOP) then you might as well offer direct access as write
get/set methods.... But if you want to ensure some kind of
behaviour is associated with the attribute then use a property
or setattr().

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

Ultimately, it's always up to the programmer how you
implement it! :-)

But some techniques make your life a bit easier is all.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list