[Numpy-discussion] Preventing an ndarray subclass from returning new subclass instances for std(), etc

Wes McKinney wesmckinn@gmail....
Sun Sep 18 15:58:52 CDT 2011


On Sun, Sep 18, 2011 at 4:25 PM, Pierre GM <pgmdevlist@gmail.com> wrote:
>
> On Sep 18, 2011, at 21:25 , Stéfan van der Walt wrote:
>
>> On Sun, Sep 18, 2011 at 9:48 AM, Keith Hughitt <keith.hughitt@gmail.com> wrote:
>>> Interesting. It works as expected when called as a method:
>>>
>>> In [10]: x = np.ma.array([[1,2,3]])
>>> In [11]: x.std()
>>> Out[11]: 0.81649658092772603
>>
>> I'm guessing that np.ma.array implements its own std function, but I
>> haven't checked.
>
> It does. np.std tries first to call the .std method of the input argument.
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>

I thought maybe you can intercept 0-dim objects and return self.item()
in array_finalize, but not dice. This is really weird:

import numpy as np

class example(np.ndarray):

    def __new__(cls, arr):
        return np.array(arr).view(cls)

    def __array_finalize__(self, obj):
        print 'foo'
        if self.ndim == 0:
            return self.item()


In [6]: foo = example(np.arange(10))
foo

In [7]: foo.std()
foo
foo
foo
foo
foo
foo
foo
Out[7]: example(2.8722813232690143)


More information about the NumPy-Discussion mailing list