[Tutor] Set and get class members

Mark Lawrence breamoreboy at gmail.com
Wed Jul 21 03:41:00 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()
>          for i in range(8):
>              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

Of course, you're trying to assign to an empty list, only then do you 
try to append to the list.  The cleanest way that I see to do what you 
want is to get your __init__ method for the Led class to set the state, 
don't do it directly in the for loop. Then if you want you can use a 
list comprehension:-

self.leds = [Led((50 + (i * 30), 50)) for i in range(8)]

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list