A class with eventhandlers ?

Farshid Lashkari flashkNO at SPAMgmail.com
Mon Jan 30 02:37:47 EST 2006


It's definitely possible, here's a small example. There are probably 
better ways to do it, but I'll let you figure that out ;)

class ErrorHandler:
	def __init__(self,method):
		self.method = method
		self.errorHook = None
		
	def onError(self,hook):
		self.errorHook = hook
		
	def __call__(self, *args, **kwargs):
		if self.errorHook:
			try:
				self.method(*args,**kwargs)
			except Exception, e:
				self.errorHook(e)
		else:
			self.method(*args,**kwargs)
				
				
class MyClass:
	def __init__(self):
		self.load = ErrorHandler(self.load)
		
	def load(self,filename):
		return self.x
	
def IOErrorHook(e):
	print 'Caught error:',e
	
c = MyClass()
c.load.onError(IOErrorHook)
c.load('filename')



More information about the Python-list mailing list