Returning same type as self for arithmetic in subclasses
Max M
maxm at mxm.dk
Sat Jan 8 11:30:19 EST 2005
Tim Peters wrote:
> Yes, and all builtin Python types work that way. For example,
> int.__add__ or float.__add__ applied to a subclass of int or float
> will return an int or float; similarly for a subclass of str. This
> was Guido's decision...
I will not discuss it with him. He is usually right :-s
> Generally speaking, no. But I'm sure someone will torture you with a
> framework that purports to make it easy <wink>.
Apparently not... But here is my solution.
If anybody is interrested. It should also be obvious what I am working on.
Btw. I really love doctests ... Unittests are a nice idea. But doctest
is a really practical solution.
###############################
class vDatetime(datetime):
"""
A subclass of datetime, that renders itself in the iCalendar datetime
format.
>>> dt = vDatetime(1970, 1,1, 12, 30, 0)
>>> str(dt)
'19700101T123000'
>>> dt2 = vDatetime(1970, 1,1, 0, 0, 0)
>>> str(dt - dt2)
'PT12H30M'
Adding is not allowed
>>> dt + dt2
Traceback (most recent call last):
...
AttributeError: 'NotImplementedType' object has no attribute 'days'
"""
def __init__(self, *args, **kwargs):
datetime.__init__(self, *args, **kwargs)
self.params = Params()
def __add__(self, other):
return self._to_vdatetime(datetime.__add__(self, other))
def __sub__(self, other):
return self._to_vdatetime(datetime.__sub__(self, other))
def _to_vdatetime(self, result):
if hasattr(result, 'timetuple'):
return vDatetime(*result.timetuple()[:6])
return vDuration(result.days, result.seconds)
def fromstring(st):
"Class method that parses"
try:
timetuple = map(int, ((
st[:4], # year
st[4:6], # month
st[6:8], # day
st[9:11], # hour
st[11:13], # minute
st[13:15], # second
)))
except:
raise ValueError, 'Wrong format'
return vDatetime(*timetuple)
fromstring = staticmethod(fromstring)
def __str__(self):
return self.strftime("%Y%m%dT%H%M%S")
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
More information about the Python-list
mailing list