Using __numpy_ufunc __ ()

I am trying to use the method __numpy_ufunc__()explained here in Numpy v1.11 docs to override the behavior of numpy ufuncs in a subclass ndarray, but it never calls a call. Although this use case is listed in the manual, I cannot find anyone who really used it __numpy_ufunc__(). Has anyone tried this? Here is a minimal example:

# Check python version
import sys
print(sys.version)

3.5.1 | Continuum Analytics, Inc. | (default, June 15, 2016 3:32:45 PM)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)

# Check numpy version
import numpy as np
print(np.__version__)

1.11.2

# Subclass ndarray as discussed in 
# https://docs.scipy.org/doc/numpy/user/basics.subclassing.html
class Function(np.ndarray):

    # Create subclass object by view
    def __new__(cls):
        obj = np.asarray([1,2,3]).view(cls)
        return obj

    # I'm not even adding anything functionality yet
    def __array_finalize(self,obj): pass

    # Override ufuncs
    def __numpy_ufunc__(ufunc, method, i, inputs, **kwargs):
        print("In PF __numpy_ufunc__")
        # do other stuff here if I want to 
        # and probably need to return a value...

# Create two Functions
f1=Function()
f2=Function()

# Check that they are correctly initialized as Function objects
# not just ndarrays
print(type(f1),type(f2))

& langle; class ' main .Function' & rangle; & langle; class ' main .Function' & rangle;

# Add using operator
f1+f2

Function ([2, 4, 6])

# Add, explicitly demanding a numpy ufunc
np.add(f1,f2)

Function ([2, 4, 6])

, , numpy . numpy __numpy_ufunc__() ( , 1.1). "In PF __numpy_ufunc__". ?

+4
1

- Numpy 1.13 :

__array_ufunc__

__numpy_ufunc__. , ndarray , None, NumPys ufuncs. Pythons __mul__ . . . API , , . . NEP .

.

+2

Source: https://habr.com/ru/post/1665933/


All Articles