python 在Python中简单实现事件驱动编程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 在Python中简单实现事件驱动编程相关的知识,希望对你有一定的参考价值。

from friend import Friend

def main():
  myFriend = Friend("john")
  myFriend.name = "mike"


if __name__ == "__main__":
  main()
from event import ObjectWithEvents

class Friend(ObjectWithEvents):

    def __init__(self, name):
        self.__name = name
        self.addEvent("changed", self.welcome)

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        if value:
          self.__name = value
          self.triggerEvent("changed")

    def welcome(self):
        print("Welcome, to a friend of mine", self.__name.title())
class ObjectWithEvents:
  
    callbacks = None
    
    def addEvent(self, eventname, callback):
        if self.callbacks is None:
            self.callbacks = {}
        if eventname not in self.callbacks:
            self.callbacks[eventname] = [callback]
        else:
            self.callbacks[eventname].append(callback)

    def triggerEvent(self, eventname):
        if self.callbacks is not None and eventname in self.callbacks:
            for callback in self.callbacks[eventname]:
                callback()

以上是关于python 在Python中简单实现事件驱动编程的主要内容,如果未能解决你的问题,请参考以下文章

twisted是python实现的基于事件驱动的异步网络通信构架。

Python并发编程-事件驱动模型

Python并发编程-事件驱动模型

python网络编程04 异步与同步编程事件驱动

事件驱动的Python实现

python IOmodel