[Tutor] Class access rules

Phil phillor9 at gmail.com
Mon Mar 7 20:08:06 EST 2022


On 8/3/22 10:55, Alan Gauld via Tutor wrote:
>
> Actually I'd advocate having on/off (and maybe toggle) methods.

That's how this thread started, I was wondering if I should have methods 
to set the LED's state rather than setting the state attribute directly. 
This is how I use the state attribute in my toggle method:

     def toggle(self):
         self.state = not self.state

I also use the LED's state to determine the LED draw fill colour.

> Those are the things you actually do with a LED.
> How you implement those methods may or may not involve
> internal state. But I have never in practice asked a LED
> for its state (unless you count looking at it to see if
> it is lit I suppose, but that should then become an isLit()
> predicate)

Perhaps I should change the name state to is_on? It would still be a 
boolean flag.

> Focusing on the internal state attribute leads to a data
> centric view of the object rather than its operational interface.
>
> But notice how a single state attribute now results in 4 operations.
>
> You could just provide two: getState/setState,

That's what I was originally asking, no doubt clumsily, "Should I modify 
the class by adding setter and getter methods instead of directly 
accessing the instance attributes?"

>   but then you move
> the understanding of how the LED operates to the user of the LED
> rather than it being intrinsic to the LED itself. Remember
> the OOP axim, "objects do it to themselves"(*)
>
> (*) Coad & Nicola in their book "Object Oriented Programming"

Thank you Alan for your time, you've given more to think about. I'm 
already thinking about the need for the following methods:

on, off, toggle, set_size, set on_colour and set_off colour. I cannot, 
at the moment, see a need for any getter methods. Currently all of this, 
except for toggle, are achieved through direct access to the attributes.

On and off methods would negate the need for a set state (or is_on) 
method or to set the state attribute directly, because the on, off and 
toggle methods would set or reset this flag.

The class constructor's current default arguments are, state=False, 
size=10, on_colour='red', off_colour='black'.

Back to the drawing board.

-- 

Regards,
Phil



More information about the Tutor mailing list