Reputation: 5549
I'm extending the datetime object because I would like to override the str method.
class MyDatetime(datetime.datetime):
def __str__(self):
return self.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
problem, is that whenever I start adding and subtracting timedeltas, I get back datetimes and not MyDatetimes. I could include a constructor for a MyDatetime from a datetime and then override the __add__
and __sub__
methods as well, but there could be others, and it just seems like there should be some easy way to deal with this... Any suggestions?
Upvotes: 2
Views: 49
Reputation: 2274
There is no easy way in your situation - you'll have to override all mathematical magic methods if you want to cover all possible situations.
There's a comprehensive list of mathematical magic methods in Python documentation:
https://docs.python.org/2.7/reference/datamodel.html#emulating-numeric-types
At least the code for those methods will be similar enough so you should be able to create them by lots of copy&paste with minor modifications.
Upvotes: 1