[Tutor] Set and get class members

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jul 19 06:35:24 EDT 2021


On 19/07/2021 06:48, Phil wrote:

> Say I wanted to set all the LED's status to false, or that of a 
> particular LED, do I need a set function or can I access the attribute 
> directly? 

Your class is defining a single Led.
You can (in Python) set the state directly ) or you can create
a set() method (not a function, they are not the same!) or you
can create a state property. The simplest route is to set it
directly.

If using a method I'd suggest a switch() method instead that
toggles state on/off. You can still force a state by direct
access when necessary.


In either case, what I have done below is not correct.
> 
> class Led:
>      def __init__(self, pos):
> 
>          self.pos = pos
>          self.state
> 
>          def setState(self, s):
>              self.state = s

By defining the method inside init() it will disappear
after the init() method completes. You need to define
it at the class level as a separate method:

class Led:
   def __init__(self...):....
   def set(...):.....

>          self.leds = list()
>          for i in range(8):
>              self.leds[i].setState(False)
>              self.leds.append(Led((50 + (i * 30), 50)))

Should a single LED know about a lot of other LEDS?
Maybe you need a separate variable that holds the list of LEDs?

[A more exotic choice would be to make the list of LEDs be
a class variable(not an instance one) and have all LEDs append
themselves to that when created. You can then create a class
method that will turn all LEDs on/off.

class LED:
    allLEDS = []  #class variable
    def __init__(self,state):
      ... init LED attributes...
      LED.allLEDS.append(self)
    def switch(self): self.state = not self.state
    @classmethod
    def switch_all(cls):
        for led in LED.allLEDS:
            led.switch()

The problem with this approach in Python is that Python
does not have reliable destructors so you cannot reliably
delete the LEDs when they are destroyed.
]

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.

-- 
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