"Latching" variables in function

Tim Chase python.list at tim.thechases.com
Wed Apr 9 09:34:26 EDT 2014


On 2014-04-08 16:09, Grawburg wrote:
> def button():
>    pushbutton = 0
>   button_value = 0
>    pushbutton=bus.read_byte_data(address,GPIOB)
>    if pushbutton > 0:
>         button_value = 1
>    return button_value
> 
> I need button_value to become '1' when the button is pressed and to
> remain '1' until the entire program (only about 25 lines) ends with
> a sys.exit()
> 
> What do I use to 'latch' button_value?

If I understand what you want, you could do something like

  class LatchButton:
    def __init__(self, address):
      self.value = 0
      self.address = address
    def __call__(self):
      if not self.value:
        if bus.read_byte_data(self.address, GPIOB) > 0:
          self.value = 1
      return self.value

  button1 = LatchButton(address1)
  button2 = LatchButton(address2)
  for i in range(10):
    print button1(), button2()
    time.sleep(3)

-tkc









More information about the Python-list mailing list