Lately I was needing to use multiple inheritance to split behaviour of a
class and modularize it.
But the problem raises when the need is to add operations to a method
already present in one of them from another.
I think the technical solution is the use of 'super'.
Then I tried to write a decorator for automatize the 'super' call,but I
failed.
Next solution is implementing the observer pattern on methods call.
I'm pretty sure there are bugs and ideas to be corrected in the next
code,any help and comment appreciated.
Regards Paolino
############### ############### ############### ############### ############### #############
''' A module collecting classes for known patterns
'''
import types
class Observer(dict):
''' A class defining some decorators for function/methods to
chain/link them when called .To do:implement pre event execution hooking'''
def __call__(self,o bserved,args,kw args):
for reaction in self.get(observ ed,()):
reaction(*args, **kwargs)
def emit(self,metho d,observed=None ):
''' A decorator for functions to signal their calling.Post hook
cablated'''
def wrapper(*args,* *kwargs):
if observed:
if type(observed) is types.MethodTyp e:
event=observed. im_func
else:
event=observed
else:
event=wrapper
result=method(* args,**kwargs)
self(wrapper,ar gs,kwargs)
return result
return wrapper
def emitOther(self, observed):
''' A decorator facility to let the function/method emit another
event (not itself)'''
def wrapEmit(method ):
return self.emit(metho d,observed)
return wrapEmit
def reactOn(self,*o bserveds):
''' a decorator to set the function/method as a reaction to
*observeds event.
Remember to use __ name mangling when working on methods to be
able to use
same reaction name on multiple class inheritances'''
def reaction(method ):
for observed in observeds:
if type(observed) is types.MethodTyp e:
observed=observ ed.im_func
self.setdefault (observed,set() ).add(method)
return method
return reaction
if __name__=='__ma in__':
observer=Observ er()
class base(object):
@observer.emit
def method(self,*ar gs,**kwargs):
print '%s.method'%str (self),args,kwa rgs
class extensionA(obje ct):
@observer.react On(base.method)
def __methodReactio n(self,*args,** kwargs):
print 'A,%s.methodRea ction'%str(self ),args,kwargs
class extensionB(obje ct):
@observer.react On(base.method)
def __methodReactio n(self,*args,** kwargs):
print 'B,%s.methodRea ction'%str(self ),args,kwargs
class applicable(base ,extensionA,ext ensionB):
@observer.react On(base.method)
def __methodReactio n(self,*args,** kwargs):
print 'applicable,%s. methodReaction' %str(self),args ,kwargs
pass
applicable().me thod('cucu')
_______________ _______________ _____
Yahoo! Messenger: chiamate gratuite in tutto il mondo
http://it.beta.messenger.yahoo.com