将 numpy 数组通过右手运算符传递后,如何访问它的属性__rsub__
?
我在 python 中编写了一个非常简单的类,它定义了两个函数:
class test(object):
def __sub__(self, other):
return other
def __rsub__(self, other):
return other
基本上他们也应该这样做。左手运算符__sub__
按预期工作,但似乎 numpy 数组在右手运算符上被剥离了它的属性
from skimage import data
from skimage.color import rgb2gray
lena = data.lena()
grayLena = rgb2gray(lena)
t = test()
## overloaded - operator
left_hand = t - grayLena
print left_hand
# Output:
#array([[ 0.60802863, 0.60802863, 0.60779059, ..., 0.64137412,
# 0.57998235, 0.46985725],
# [ 0.60802863, 0.60802863, 0.60779059, ..., 0.64137412,
# 0.57998235, 0.46985725],
# [ 0.60802863, 0.60802863, 0.60779059, ..., 0.64137412,
# 0.57998235, 0.46985725],
# ...,
# [ 0.13746353, 0.13746353, 0.16881412, ..., 0.37271804,
# 0.35559529, 0.34377725],
# [ 0.14617059, 0.14617059, 0.18730588, ..., 0.36788784,
# 0.37292549, 0.38467529],
# [ 0.14617059, 0.14617059, 0.18730588, ..., 0.36788784,
# 0.37292549, 0.38467529]])
right_hand = grayLena - t
print right_hand
# Output:
# array([[0.6080286274509803, 0.6080286274509803, 0.6077905882352941, ...,
# 0.6413741176470589, 0.5799823529411765, 0.4698572549019608],
# [0.6080286274509803, 0.6080286274509803, 0.6077905882352941, ...,
# 0.6413741176470589, 0.5799823529411765, 0.4698572549019608],
# [0.6080286274509803, 0.6080286274509803, 0.6077905882352941, ...,
# 0.6413741176470589, 0.5799823529411765, 0.4698572549019608],
# ...,
# [0.1374635294117647, 0.1374635294117647, 0.1688141176470588, ...,
# 0.3727180392156863, 0.35559529411764706, 0.34377725490196076],
# [0.1461705882352941, 0.1461705882352941, 0.18730588235294118, ...,
# 0.3678878431372549, 0.37292549019607846, 0.3846752941176471],
# [0.1461705882352941, 0.1461705882352941, 0.18730588235294118, ...,
# 0.3678878431372549, 0.37292549019607846, 0.3846752941176471]], dtype=object)
所以这两个操作的区别在于__rsub__
接收一个 dtype=object 的数组。如果我只是设置这个数组的 dtype,一切都会正常工作。
但是,它仅适用于 . 之外的返回值__rsub__
。在我里面我__rsub__
只有垃圾,我无法转换回来,即如果我这样做
npArray = np.array(other, dtype=type(other))
我得到一个类型的一维数组(在我的例子中是浮点数)。但是由于某种原因,形状信息丢失了。有没有人这样做或知道如何访问数组的原始属性(形状和类型)?