[Python-Dev] subclassing builtin data structures (original) (raw)

Alexander Belopolsky alexander.belopolsky at gmail.com
Sat Feb 14 19:26:36 CET 2015


On Sat, Feb 14, 2015 at 7:23 AM, Steven D'Aprano <steve at 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.frombytes(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. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20150214/f9a2d709/attachment.html>



More information about the Python-Dev mailing list