Well, this is the right way to do this (I would just split the converter method into two). Python helps reduce code duplication:
from datetime import * def convproxy(methods,converter): def f(cls): def _proxyfactory(method): def _convproxy(self,*args,**kwargs): return converter(getattr(super(cls,self),method)(*args,**kwargs)) return _convproxy for m in methods: setattr(cls,m,_proxyfactory(m)) return cls return f @convproxy(('__add__','__sub__'),lambda d:mydatetime(d.timetuple()[:6])) class mydatetime(datetime): pass @convproxy(('__add__','__sub__','__div__','__rmul__','__mul__'),\ lambda t:mytimetuple(t.days,t.seconds)) class mytimedelta(timedelta): pass
The hidden code under convproxy
is just a smart-aleck way to create the specified methods when creating a class, each of which calls the superclass method and subclasses the result using the specified conversion function.
source share