import numpy as np
class AutoArray2(np.ndarray):
def __new__(cls, input_array):
# Input array is an already formed ndarray instance
# We first cast to be our class type
obj = np.asarray(input_array).view(cls)
return obj
def __array_finalize__(self, obj):
if obj is None: return
def __setitem__(self, coords, value):
print("HERE")
a = np.array([[1,2],[2,3]])
b = AutoArray2(a)
b[0,0] = 1
子类化numpy数组有点棘手。 Stefan van der Walt's slides和{a2} 如果你想子类化的话,这是一个很好的开始。在
收益率
^{pr2}$关键因素是对
view(cls)
的调用。如果没有它,您将返回一个普通的ndarray
,而不是AutoArray2实例。在而且,
a[0,0] = 1
正在使用a
原版ndarray
。要使用b
的__setitem__
,您需要b[0,0] = 1
。在相关问题 更多 >
编程相关推荐