[Tutor] Set and get class members

Alan Gauld alan.gauld at yahoo.co.uk
Wed Jul 21 03:46:55 EDT 2021


On 21/07/2021 07: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.
> 
> This is what has been suggested;
> 
>          self.leds = list()

This should NOT be inside the class, it should be external. So:

leds = list()   # create empty list

>          for i in range(8):
>              self.leds[i].self.state = False

You don't need the self (self is like 'this' in C++) and
you can't use indexing until you've filled the list.
So append the LEDs or use a list comprehension:

leds = [Led(...) for _ in range(8)]  # create list of 8 LEDs

Then you can iterate over them:

 for led in leds:
     led.state  = False   # turn it off.

>              self.leds.append(Led((50 + (i * 30), 50))) # this results in 8 equally spaced LEDs

You could do it this way but this line needs to be first.
You can't index the list before adding the item.

for i in range(8):
    leds.append(Led(...))
    leds[i].state = False

But its less pythonic to use indexing like that.

> No matter how I try to set the state of a LED the error message is:
> 
> IndexError: list assignment index out of range

You just need to create the Led and put it in the list
before you try to access it

> This is how I came up with a working solution in C++ using set methods 

The set methods are irrelevant you could use direct access in C++ too,
just make the state public.

>    l = new Led[num_leds];
> 
> 
>    for (int i = 0; i < num_leds; i++)
>    {
>      l[i] = new Led(60 + (i * 40), 120);

Here you create the led and add it to the array.

>      l[i].setState(false);

Now you access it.
The opposite way round to what you did in python.
And the correct way.

> All I need to do is set the state of say LED[3].

Oncer you have created and added them to the list you can use indexing:

led[3].state = True

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list