Button class with callbacks
📖 Scenario: You are building a simple program to handle button presses on a Raspberry Pi. Buttons can do different things when pressed, so you want to create a Button class that can run a special function (called a callback) whenever the button is pressed.This is like having a doorbell that plays a different sound depending on who is at the door. The button press triggers the sound.
🎯 Goal: Create a Button class that stores a callback function. When the button is pressed, it should run the callback. You will then create a button instance, assign a callback, and simulate a button press to see the callback run.
📋 What You'll Learn
Create a
Button class with an __init__ method that takes a callback parameter and stores it.Add a
press method to the Button class that calls the stored callback function.Create a function called
say_hello that prints 'Hello! Button pressed.'.Create a
Button instance called button with say_hello as the callback.Call the
press method on the button instance to run the callback.Print the output of the callback when the button is pressed.
💡 Why This Matters
🌍 Real World
Buttons on Raspberry Pi or other devices often need to run specific code when pressed. Using callbacks lets you easily change what happens without rewriting the button code.
💼 Career
Understanding callbacks and event-driven programming is important for embedded systems, hardware interfacing, and GUI programming jobs.
Progress0 / 4 steps