Callback in Python
What are Callbacks in Python?
A callback is a function that is passed as an argument to another function and is called later inside that function to complete a specific task.
In simple terms:
A callback is a function you give to another function so that it can call it when needed.
✅ Why Use Callbacks?
-
To customize the behavior of a function
-
To handle events (e.g., in GUIs or web frameworks)
-
To process results (e.g., in asynchronous programming)
-
To simplify code reuse and abstraction
✅ Basic Example of a Callback Function
Output:
Hello, Alice!📝 Here:
-
greet
is a callback function. -
process_user
accepts the callback and calls it with data.
✅ Example: Using Callbacks to Customize Behavior
📝 square
and cube
are callback functions passed to apply_function
.
✅ Real-World Example: Sorting with a Callback (Key Function)
📝 The lambda
here acts as a callback passed to sorted()
.
✅ Summary
Term | Meaning |
---|---|
Callback | A function passed as an argument |
Used in | Sorting, GUI events, web apps, async programming |
Benefit | Flexible, reusable, customizable behavior |
Comments
Post a Comment