On Sat, Feb 14, 2015 at 7:23 AM, Steven D'Aprano <st...@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(_)
<class '__main__.Int'>

>>> Int(1) + 1
2
>>> type(_)
<class 'int'>

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.
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to