Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当对ndarray的子类调用时,Numpy函数返回数组类实例_Python_Numpy - Fatal编程技术网

Python 当对ndarray的子类调用时,Numpy函数返回数组类实例

Python 当对ndarray的子类调用时,Numpy函数返回数组类实例,python,numpy,Python,Numpy,某些numpy函数(逻辑上)返回标量: >>> my_arr = np.ndarray(shape=(1,)) >>> type(np.max(my_arr)) <type 'numpy.float64'> my_arr=np.ndarray(shape=(1,)) >>>类型(np.max(my_arr)) 但仅当使用ndarray而不是子类调用时: >>> class CustomArray(np.ndarray): ..

某些numpy函数(逻辑上)返回标量:

>>> my_arr = np.ndarray(shape=(1,))
>>> type(np.max(my_arr))
<type 'numpy.float64'>
my_arr=np.ndarray(shape=(1,)) >>>类型(np.max(my_arr)) 但仅当使用ndarray而不是子类调用时:

>>> class CustomArray(np.ndarray):
...     pass
>>> my_arr = CustomArray(shape=(1,))
>>> type(np.max(my_arr))
<class '__main__.CustomArray'>
类CustomArray(np.ndarray): ... 通过 >>>my_arr=CustomArray(形状=(1,)) >>>类型(np.max(my_arr)) 为什么会这样?我希望两者都返回标量(类型为
),或者前者返回
np.ndarray
实例,后者返回
CustomArray
实例。但是,我得到了这两种行为的组合。我可以通过更改自己的类来更改这种行为吗

在讨论子类化ndarray()的文档页面上,我没有看到任何可以解释这一点的内容

(运行Python 2.7.10,numpy 1.9.2,以防万一。)

这是因为
max()
CustomArray
中没有重载。如果您尝试使用它,
my_array.max()
将返回CustomArray的对象,而不是标量

my_array = CustomArray(shape=(1,))
print my_array.max()
>> CustomArray(9.223372036854776e+18)
np.max
内部调用
np.amax
,最终调用
np.max.reduce
。这是map reduce的标准
reduce
,返回max返回的基本对象。因此,
np.max
返回的类型实际上就是
max()返回的类型
对对象调用的方法。您可以将其重写为:

class CustomArray(np.ndarray):
   def max(self, axis, out):
      return np.ndarray(self.shape, buffer=self).max(axis, out)

type(np.max(my_arr))
>> numpy.float64

诀窍是将self向上转换为
np.ndarray
,然后找到使用它的max。

我猜我必须改变
ndarray
实例得到的几乎所有方法(我只是以
max
为例)此外,如果子类实际上没有改变任何行为,那么这并不能回答为什么子类的实例的行为与ndarray的实例不同的问题。是的,如果您想要正确的返回类型,您可能必须更新每个相关的方法。类体不更新任何内容,但会更新max()的默认重写(以及其他方法,如sum())与基本np.ndarray不同。为什么它们不同?是否在
ndarray.max
中有明确的检查来检查
self
是否实际上是
ndarray
的一个实例,而不是一个子类或什么?查看
np.matrix
masked
的代码,看看它们是如何处理的。