python – 使用__numpy_ufunc __()
作者:互联网
我正在尝试使用here in the Numpy v1.11 docs解释的__numpy_ufunc __()方法来覆盖ndarray的子类上的numpy ufuncs的行为,但它似乎永远不会被调用.尽管指南中列出了这个用例,但我找不到任何实际使用__numpy_ufunc __()的例子.有没人试过这个?这是一个最小的例子:
# Check python version
import sys
print(sys.version)
3.5.1 | Continuum Analytics,Inc.| (默认,2016年6月15日,15:32:45)
[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
功能([2,4,6])
# Add, explicitly demanding a numpy ufunc
np.add(f1,f2)
功能([2,4,6])
很明显,子类化工作,并使用numpy在幕后添加数组.我正在使用一个足够新的numpy版本来使用__numpy_ufunc __()功能(根据该文档页面,它是v1.11中的新功能).但是这段代码永远不会输出“In PF __numpy_ufunc__”.是什么赋予了?
解决方法:
此功能最终于Numpy 1.13以新名称发布:
__array_ufunc__
addedThis is the renamed and redesigned
__numpy_ufunc__
. Any class, ndarray subclass or not, can define this method or set it to None in order to override the behavior of NumPy’s ufuncs. This works quite similarly to Python’s__mul__
and other binary operation routines. See the documentation for a more detailed description of the implementation and behavior of this new option. The API is provisional, we do not yet guarantee backward compatibility as modifications may be made pending feedback. See the 07001 and 07002 for more details.
这应该可以解决这个问题.
标签:python,numpy,numpy-ufunc 来源: https://codeday.me/bug/20190701/1351547.html