【发布时间】:2021-01-13 09:43:57
【问题描述】:
假设我有一个array,它是np.ndarray 类的子类实例:
class RealisticInfoArray(np.ndarray):
def __new__(cls, input_array, info=None):
obj = np.asarray(input_array).view(cls)
obj.info = info
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'info', None)
def __reduce__(self):
print('in reduce')
# Get the parent's __reduce__ tuple
pickled_state = super(RealisticInfoArray, self).__reduce__()
# Create our own tuple to pass to __setstate__
new_state = pickled_state[2] + (self.info,)
# Return a tuple that replaces the parent's __setstate__ tuple with our own
return (pickled_state[0], pickled_state[1], new_state)
def __setstate__(self, state):
print('in set_state')
self.info = state[-1] # Set the info attribute
# Call the parent's __setstate__ with the other tuple elements.
super(RealisticInfoArray, self).__setstate__(state[0:-1])
def tofile(self, fid, sep="", format="%s"):
super().tofile(fid, sep, format)
print('in tofile')
def tobytes(self, order='C'):
super().tobytes(order)
print('in tobytes')
array = RealisticInfoArray(np.zeros((7, 9, 13)), info='tester')
方法__reduce__、__setstate__、tofile 和tobytes 包括在内,因为我认为它们参与了我想要执行的保存:我想将数组存储在磁盘上(通过任何@ 987654329@、np.savez、np.savez_compressed) 并将其加载回来,同时保留该对象的类和所有自定义属性。
我已经尝试过another SO question 的方法,但这不起作用,因为我想使用np 函数,而不是pickle 或dill。另外,我从那里借用了 MWE 的子类。
另外一点信息是,实际的保存是由np.lib.npyio.format.write_array 执行的,这似乎不允许存储数据的任何自定义行为。
所以,我的问题是是否可以保留存储数组的类,如果可以,如何做?
【问题讨论】: