[Python-Dev] subclassing builtin data structures
Steven D'Aprano
steve at pearwood.info
Sun Feb 15 03:04:06 CET 2015
On Sat, Feb 14, 2015 at 01:26:36PM -0500, Alexander Belopolsky wrote:
> 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.
But in datetime, instance methods *do*.
Sorry that my example with .today() was misleading.
py> from datetime import datetime
py> class MyDatetime(datetime):
... pass
...
py> MyDatetime.today()
MyDatetime(2015, 2, 15, 12, 45, 38, 429269)
py> MyDatetime.today().replace(day=20)
MyDatetime(2015, 2, 20, 12, 45, 53, 405889)
> In the case of int, there is a good reason for this behavior - bool. In
> python, we want True + True == 2.
Sure. But bool is only one subclass. I expect that it should be bool's
responsibility to override __add__ etc. to return an instance of the
parent class (int) rather have nearly all subclasses have to override
__add__ etc. to return instances of themselves.
--
Steve
More information about the Python-Dev
mailing list