First and foremost, What are events?
Events are the constructs that enable a class to notify other classes when something of interest takes place.
In the layman language, it is basically similar to raising a flag to signal others that something of interest has happened.
When to use events in Python?
Event-based programming is predominantly used while working with UI(user interface) where different components need to be signaled of some occurrence. for e.g imagine a Currency Converter which needs to output the converted currency in box2 while the user enters some value in the box1.
How does the box2 get to know that the user has entered something in the box1 and what needs to be done in the response to it
This is one of the most basic examples of the event based programming.
Another possible example could be HomeSecurity System where some possible actions such as the alarm need to be raised, the message needs to be sent to the owner and Police need to be informed about the possible theft are to be performed on the breach of the lock. These type of systems can be easily designed using the event based mechanism where the event will be raised as soon as someone breaks the lock and in turn notifying the event handlers to play their part.
Now, in this post, we will use the latter example to understand how such events can be designed in Python where it is not supported by default.
police have been informed owner has been messaged about the possible theft Alarm has started
The class that raises the event is called the publisher and the classes that receive the event are called subscribers.
Also, an event can have multiple subscribers and a subscriber can handle multiple events from multiple publishers
This article is contributed by Ankit Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Python | Convert list to Python array
- Reading Python File-Like Objects from C | Python
- Python | Merge Python key values to list
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- Python Set | pop()
- bin() in Python
- max() and min() in Python
- gcd() in Python