First of all, what are events?
Events — these are constructs that allow a class to notify other classes when something interesting happens.
In layman's terms, this is basically like raising a flag to signal to others that something interesting has happened.
When to use events in Python? strong>
Event-based programming is primarily used when working with a user interface (UI), where various components must signal some occurrence. for example, imagine a currency converter that should output the converted currency into box2 while the user enters some value into box1.
How box2 knows that the user has entered something into box1 and what needs to be done in response to it.
This is one of the most basic examples of event-based programming.
Another possible example would be be a HomeSecurity system in which it is necessary to raise some possible actions, such as an alarm, send a message to the owner, and the police should be informed about the possible theft when breaking the lock. Systems of this type can be easily designed using an event-driven mechanism, where an event will be triggered as soon as someone breaks the lock, and in turn will notify the event handlers to play their part.
Now in this post we will use the last example to understand how such events can be generated 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.
Additionally, an event can have multiple subscribers, and a subscriber can handle multiple events from multiple publishers.
This article is provided by Ankit Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.