[Tutor] Set and get class members
dn
PyTutor at DancesWithMice.info
Wed Jul 21 04:28:16 EDT 2021
On 21/07/2021 18.27, Phil wrote:
> On 19/7/21 8:35 pm, Alan Gauld via Tutor wrote:
>>
>> My personal recommendation is to keep it as simple as possible.
>> Access the state attribute directly and have the LEDs stored
>> in a global list variable.
Didn't we cover this the other day in "[Tutor] object does not support
item assignment"?
Class 1: an LED
- can be replicated as many times as there are LEDs to represent.
Class 2 or more likely a list: representing the LED array
> This is what has been suggested;
>
> self.leds = list()
no need for "self."
"self" is only used inside the LED class!
> for i in range(8):
what might happen inside this loop:
- instantiate an LED
- append it to the list (or collection class)
> self.leds[i].self.state = False # this is not correct. If
> state is True then the LED is on.
> self.leds.append(Led((50 + (i * 30), 50))) # this results in
> 8 equally spaced LEDs
>
> Is this what you have in mind?
>
> No matter how I try to set the state of a LED the error message is:
>
> IndexError: list assignment index out of range
Once the list of LED objects has been established, access will be of the
form:
list[ index ].turn_on()
where list[ 0 ] etc are LED objects. Thus by choosing the list-index the
code will direct itself to a particular LED.
If you want each LED to be addressable by some sort of name, then don't
use a list, use a dict instead:
dict[ name ].turn_on()
> This is how I came up with a working solution in C++ using set methods
> quite some time ago.
>
> l = new Led[num_leds];
>
>
> for (int i = 0; i < num_leds; i++)
> {
> l[i] = new Led(60 + (i * 40), 120);
> l[i].setState(false);
> l[i].setLedSize(30);
> l[i].setOnColour(green);
> l[i].setOffColour(black);
> }
>
> All I need to do is set the state of say LED[3].
In the __init__() for the LED class, I would set these as default
values, rather than setting them dynamically.
> I've been sitting in a broken down motorhome for most of the day and my
> head is in a bit of a spin which could be why I'm having trouble with
> this simple problem.
Know the feeling, even without a motorhome...
--
Regards,
=dn
More information about the Tutor
mailing list