为什么从numpy数组继承的类的方法返回不同的东西? [英] Why do methods of classes that inherit from numpy arrays return different things?
问题描述
让我们看一下numpy数组的一些非常简单的行为:
Let's look at some very simple behaviour of numpy arrays:
import numpy as np
arr = np.array([1,2,3,4,5])
max_value = arr.max() # returns 5
现在,我创建一个继承自np.ndarray
的类:
Now I create a class which inherits from np.ndarray
:
class CustomArray(np.ndarray):
def __new__(cls, *args, **kwargs):
obj = np.array(*args, **kwargs).view(cls)
return obj
new_arr = CustomArray([1,2,3,4,5])
我实际上并没有改变任何行为-我只是在名义上改变了对象是什么类.
I haven't actually changed any behaviour - I just made a nominal change in what class the object is.
但是:
new_max_value = new_arr.max() # returns CustomArray(5)
返回值是一个CustomArray
实例?为什么? arr.max()
没有返回np.ndarray
实例,只是一个简单的numpy整数.
The return value is an CustomArray
instance? Why? arr.max()
didn't return a np.ndarray
instance, just a plain numpy integer.
同样,为什么arr == new_arr
和new_arr == arr
都返回CustomArray
实例?前一个调用arr.__eq__(new_arr)
不应返回一个np.ndarray
实例吗?
Similarly, why do both arr == new_arr
and new_arr == arr
return CustomArray
instances? Shouldn't the former call arr.__eq__(new_arr)
, which should return a np.ndarray
instance?
请注意,为了方便构造函数,我重写了__new__
方法.例如. np.array([1,2,3,4,5])
的等价物可以是CustomArray([1,2,3,4,5])
,而如果我明确地继承自np.ndarray
,则必须执行类似new_arr = CustomArray((5,))
的操作; new_arr[:] = np.array([1,2,3,4,5])
.
Note that I override the __new__
method for the sake of easy constructors. E.g. the equivalent of np.array([1,2,3,4,5])
can just be CustomArray([1,2,3,4,5])
, whereas if I plainly inherit from np.ndarray
I'd have to do something like new_arr = CustomArray((5,))
; new_arr[:] = np.array([1,2,3,4,5])
.
推荐答案
在numpy文档之后: array_wrap 在numpy ufuncs和其他numpy函数的末尾被调用,以允许子类设置返回值的类型以及更新属性和元数据.
Following the numpy docs: array_wrap gets called at the end of numpy ufuncs and other numpy functions, to allow a subclass to set the type of the return value and update attributes and metadata.
class CustomArray(np.ndarray):
def __new__(cls, a, dtype=None, order=None):
obj = np.asarray(a, dtype, order).view(cls)
return obj
def __array_wrap__(self, out_arr, context=None):
return np.ndarray.__array_wrap__(self, out_arr, context)
c = CustomArray([1,2,3,4])
c.max() # returns 4
这篇关于为什么从numpy数组继承的类的方法返回不同的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!