Re: [Python-Dev] subclassing builtin data structures

2015年2月14日 12:49:46 -0800

On Sat, Feb 14, 2015 at 2:36 PM, Georg Brandl <[email protected]> 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.])
_______________________________________________
Python-Dev mailing list
[email protected]
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