在Python中模拟事件
首先,什么是事件?
事件是使一个类能够在感兴趣的事情发生时通知其他类的构造。
在通俗的语言中,它基本上类似于举起旗帜来向其他人表示感兴趣的事情发生了。
何时在Python中使用事件?
基于事件的编程主要在使用 UI(用户界面)时使用,其中不同的组件需要发出某些事件的信号。例如,想象一个货币转换器需要在 box2 中输出转换后的货币,而用户在 box1 中输入一些值。
box2 如何知道用户在 box1 中输入了一些内容,以及在响应中需要做什么。
这是基于事件的编程最基本的例子之一。
另一个可能的例子是家庭安全系统,其中一些可能的动作,例如需要发出警报,需要将消息发送给所有者,并且需要通知警方关于可能的盗窃将在违反锁。这些类型的系统可以使用基于事件的机制轻松设计,一旦有人打破锁,就会引发事件,然后通知事件处理程序发挥他们的作用。
现在,在这篇文章中,我们将使用后一个示例来了解如何在默认情况下不支持的Python中设计此类事件。
Python3
class Event(object):
def __init__(self):
self.__eventhandlers = []
def __iadd__(self, handler):
self.__eventhandlers.append(handler)
return self
def __isub__(self, handler):
self.__eventhandlers.remove(handler)
return self
def __call__(self, *args, **keywargs):
for eventhandler in self.__eventhandlers:
eventhandler(*args, **keywargs)
class Police(object):
def __init__(self, policeTelephoneNo):
self._telephone = policeTelephoneNo
def CallPolice(self):
print ("police have been informed")
class Owner(object):
def __init__(self, ownerMobile):
self.__mobile = ownerMobile
def Message(self):
print ("owner has been messaged about the possible theft")
class Alarm(object):
def StartAlarm(self):
print ("Alarm has started")
# LockClass
class Lock(object):
def __init__(self):
self.OnLockBroken = Event()
def LockBroken(self):
# This function will be executed once a lock is broken and will
# raise an event
self.OnLockBroken()
def AddSubscribersForLockBrokenEvent(self,objMethod):
self.OnLockBroken += objMethod
def RemoveSubscribersForLockBrokenEvent(self,objMethod):
self.OnLockBroken -= objMethod
def Simulation():
# In the simulation we have a lock
# which will be broken and the object of Police
# owner and Alarm classes which are
# to be notified as soon as lock is broke
# Required objects
godrejLockObj = Lock()
localPoliceObj = Police(100)
ownerObj = Owner(99999999)
mainDoorAlarmObj = Alarm()
# Setting these objects to receive the events from lock
godrejLockObj.AddSubscribersForLockBrokenEvent(localPoliceObj.CallPolice)
godrejLockObj.AddSubscribersForLockBrokenEvent(ownerObj.Message)
godrejLockObj.AddSubscribersForLockBrokenEvent(mainDoorAlarmObj.StartAlarm)
# Now the Lock is broken by some burglar
# thus LockBroken function will be called
godrejLockObj.LockBroken()
# All three notifications must be printed
# as soon as Lock is broken now
# You can also remove any receiver by
# calling the RemoveSubscribersForLockBrokenEvent
godrejLockObj.RemoveSubscribersForLockBrokenEvent(mainDoorAlarmObj.StartAlarm)
if __name__ == "__main__":
Simulation()
输出:
police have been informed
owner has been messaged about the possible theft
Alarm has started