Subtypingclassing ndarray - 如何从正常的ndarray构造

时间:2015-03-30 14:55:22

标签: python numpy subtyping

请考虑以下代码:

class imarray(np.ndarray):
    def __new__(subtype, shape, dtype=float, buffer=None, offset=0,
          strides=None, order=None):
        if isinstance(shape, np.ndarray):
            obj = shape #doesn't convert subtype.......
        else:
            obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides,
                             order)
        return obj

    def __getitem__(self, key):
        return np.ndarray.__getitem__(self, key)





z = np.zeros([2,3])
x = imarray((2,3))
y = imarray(z)

print(y, type(y))
print(x, type(x))

y = imarray(z)应该只创建一个副本并更改数组的类型。 (但是imarray是ndarray的子​​类,无论如何都应该可以工作)。

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

尝试:

obj = shape.view(imarray)