I'm trying to extend the datetime.date
class do allow adding int
s instead of working with timedelta
objects:
class Date(datetime.date):
def __add__(self, other):
if isinstance(other, int):
other = datetime.timedelta(days=other)
return super(Date, self).__add__(other)
The problem is that the __add__()
method above will return an instance of datetime.date
instead of a Date
.
From my understanding, there is no way to make super().__add__()
aware of the Date
type. The most elegant solution is to copy the entire __add__()
method from datetime.date
and add my extra bit of code. Is there a way to cast a datetime.date
object to a Date
object in the Date.__add__()
method?
Here is a snippet to highlight the issue:
D = Date(2000,1,1)
d = D + 1
type(d) # datetime.date instead of Date
EDIT: My first solution after looking at datetime.py (search for "class date") is to do this:
class Date(datetime.date):
def __add__(self, other):
if isinstance(other, int):
other = datetime.timedelta(days=other)
d = super(Date, self).__add__(other)
self.__year = d.year
self.__month = d.month
self.__day = d.day
return self # this is of type datetime.date
OK, I thought I'd point out that my first try was this:
class Date(datetime.date):
def __add__(self, other):
if isinstance(other, int):
other = datetime.timedelta(days=other)
d = super(Date, self).__add__(other)
d.__class__ = Date
return d
which will not work because (as I suspected) the datetime module is in C and according to this post for such types you cannot assign to __class__
. I am a bit confused what the code in datetime.py is for then.