我想制作类结构,其中流程由事件的生成控制。为此,我做了以下事情:
class MyEvent:
EventName_FunctionName = {}
@classmethod
def setup(cls, notificationname, functionname):
if notificationname in MyEvent.EventName_FunctionName.keys():
MyEvent.EventName_FunctionName[notificationname].append(functionname)
else:
MyEvent.EventName_FunctionName[notificationname] = [functionname]
@classmethod
def runonnotification(cls, notificationname, *args):
thisfunclist = MyEvent.EventName_FunctionName[notificationname]
for func in thisfunclist:
if len(args) > 0:
func(*args)
else:
func()
然后按以下方式使用它:
from FirstEventClass import MyEvent
class simpleexample:
def __init__(self,a = 1, b = 2):
simpleexample.a = a
simpleexample.b = b
MyEvent.setup('greater than 100',self.printerror)
MyEvent.setup('dont do negative',self.negation)
MyEvent.setup('many values recieved',self.handlemultipleupdates)
def updation(self,updateval):
if updateval > 100:
MyEvent.runonnotification('greater than 100',updateval)
self.a = updateval
if updateval < 0:
MyEvent.runonnotification('dont do negative')
def multipleupdates(self, a, b):
MyEvent.runonnotification('many values recieved', a , b)
def printerror(self,data):
print ' something has gone wrong' ,data
def negation(self):
print 'negation enter'
self.a = -self.a
def handlemultipleupdates(self, a , b):
print 'wow'
self.a = a
self.b = b
但是,我的问题是,基本上所有这些事件都是函数调用,不久之后,我构建了一大堆递归调用。如何在通知事件的同时退出函数,或者继续在后台线程上运行现有函数。