我正在尝试创建一个numpy.ndarray子类,它具有我的应用程序所需的不同属性和更多功能。 我仍然很难分配数据类型。
class Vector(np.ndarray):
def __new__(cls, value, *args, **kwargs):
return np.asarray(value).view(cls)
def __init__(self, value, type=float):
self.set_type(type)
def set_type(self, type):
assert type in (int, float, complex, str), "type can only be int, float, complex or str, %r is given"%type
self.astype(type, copy=False)
这是一个表明类型没有改变的例子
a = Vector([1,2,3], type=str)
print a, a.dtype, a.type
>> [1 2 3] int32 <type 'str'>
答案 0 :(得分:0)
您需要确保您的实例已经使用正确的dtype
创建,i。即在__new__()
期间。您之后无法更改dtype
(除了创建新视图或副本,但不再是同一个实例)。
请改为尝试:
class Vector(np.ndarray):
def __new__(cls, data, dtype=None, copy=True):
return np.array(data, dtype=dtype, copy=copy).view(type=cls)
def __array_finalize__(self, obj):
assert issubclass(self.dtype.type, (np.number, np.character)), \
"dtype can only be number or character, %s was given" % (self.dtype,)
除非原始ndarray的dtype
与请求的dtype
相同(或者保留默认值),否则它将始终返回原始数据的副本和< / strong> copy=False
。
请注意,我将类型断言放入__array_finalize__()
方法。这是为了确保在所有3种情况下都会调用它:使用Vector
创建新的np.ndarray.__new__(Vector, ...)
实例时,从另一个ndarray创建类型为Vector
的视图时以及切片时{ {1}}实例。在所有3个案例中,它将由numpy自动调用。如果你想断言向量是严格的一维的,你也可以把它放到这个函数中。