(original) (raw)
On Sat, Feb 14, 2015 at 7:23 AM, Steven D'Aprano <steve@pearwood.info> wrote:
Why can't int, str, list, tuple etc. be more like datetime?
They are. In all these types, class methods call subclass constructors but instance methods don't.
>>> class Int(int):
... pass
...
>>> Int.from\_bytes(bytes(\[1,2,3\]), 'big')
66051
>>> type(\_)
>>> Int(1) + 1
2
>>> type(\_)
In the case of int, there is a good reason for this behavior - bool. In python, we want True + True == 2\. In numpy, where binary operations preserve subclasses, you have
>>> import numpy
>>> numpy.bool\_(1) + numpy.bool\_(1)
True
I don't see a similar argument for the date class, however. Given date.{to|from}ordinal(), date subclasses are pretty much bound to have timedelta addition satisfy (d + td).toordinal() == d.toordinal() + td.days. Any other definition would be fighting the baseclass design and would be better implemented via containment.