[Python-Dev] subclassing builtin data structures
Alexander Belopolsky
alexander.belopolsky at gmail.com
Sat Feb 14 21:47:28 CET 2015
On Sat, Feb 14, 2015 at 2:36 PM, Georg Brandl <g.brandl at gmx.net> wrote:
> > 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 think numpy.bool_ subclasses some class like numpy.int_.
And numpy.bool_ subclasses don't preserve type in addition:
>>> import numpy
>>> class Bool(numpy.bool_):
... pass
...
>>> numpy.bool_.mro()
[<class 'numpy.bool_'>, <class 'numpy.generic'>, <class 'object'>]
>>> Bool(1) + Bool(1)
True
>>> type(_)
<class 'numpy.bool_'>
So there goes my theory. :-)
I think all these examples just highlight the need for a clear guidance
when self.__class__() can be called in base classes to construct instances
of derived classes.
Apparently numpy has it both ways. One way for scalars (see above) and the
other for arrays:
>>> class Array(numpy.ndarray):
... pass
...
>>> a = Array(1)
>>> a[0] = 1
>>> a+a
Array([ 2.])
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150214/de330263/attachment.html>
More information about the Python-Dev
mailing list