Bird
0
0

You want to create a Button class that supports both on_press and on_release callbacks. Which code correctly implements this so pressing and releasing the button calls the right functions?

hard📝 Application Q15 of 15
Raspberry Pi - gpiozero Library

You want to create a Button class that supports both on_press and on_release callbacks. Which code correctly implements this so pressing and releasing the button calls the right functions?

class Button:
    def __init__(self):
        # What should go here?
    def press(self):
        # What should go here?
    def release(self):
        # What should go here?

button = Button()
button.on_press = lambda: print('Pressed')
button.on_release = lambda: print('Released')

button.press()
button.release()
AInitialize on_press and on_release as True; check if True before calling
BInitialize on_press and on_release to empty strings; print them in press and release
CDo not initialize callbacks; call them directly in press and release methods
DInitialize on_press and on_release to None; call them if set in press and release methods
Step-by-Step Solution
Solution:
  1. Step 1: Initialize callbacks properly

    Set self.on_press and self.on_release to None in __init__ to indicate no function assigned yet.
  2. Step 2: Call callbacks safely in methods

    In press and release, check if the callback is not None before calling it to avoid errors.
  3. Final Answer:

    Initialize on_press and on_release to None; call them if set in press and release methods -> Option D
  4. Quick Check:

    Initialize None and check before call = D [OK]
Quick Trick: Set callbacks to None and check before calling [OK]
Common Mistakes:
  • Using wrong default values like empty strings or True
  • Calling callbacks without checking if assigned
  • Not supporting both press and release callbacks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes