python事件驱动的小例子

首先我们写一个超级简单的web框架

event_list = []
#这个event_list中会存放所有要执行的类


def run():
    for event in event_list:
        obj = event()
        #实例化这个类
        obj.execute()
        #执行类的execute方法


class BaseHandler(object):
    """
    用户必须要继承该类,从而规范所有类的方法,类似于接口的功能
    用户在自己的类中必须要定义这个execute函数,否则会报错
    """
    def execute(self):
        raise Exception("你必须要重写execute函数")

 

在这个框架中注册我们自己的类,并且执行

import fram

class MyHandler(fram.BaseHandler):
    # pass
    def execute(self):
         print("event_drive execute MyHandler")


fram.event_list.append(MyHandler)
fram.run()


"""
解释一下上面的代码,我们用一个web框架来解释
如果我们想把自己自己的事件注册web框架中
1、必须要自己写一个类,这个类就是要注册web框架中
2、但是这个类必须要继承BaseHandler
3、类中必须要写execute这个方法,如果不写的话就会执行fram中的execute方法
4、然后把类似注册到event_list中
5、然后执行fram的run方法
"""

  

原文地址:https://www.cnblogs.com/bainianminguo/p/7476381.html