【发布时间】:2019-02-01 19:28:27
【问题描述】:
我腌制了一个派生自 ndarray 的类的实例,但在腌制/取消腌制期间丢失了属性。下面是用于说明问题的简化代码。我不明白:
- 为什么泡菜转储/加载中不包含“属性”?我需要做什么才能将其包含在内?
- 为什么在转储期间不调用 __getstate__() 以便我可以添加缺少的“atrrib”? __setstate__() 被调用。状态是如何设置的?我的想法是我会在 get 状态中添加“attrib”,以便稍后进行设置。
import numpy as np
import pickle
class Xndarray(np.ndarray):
def __new__(cls, **kwargs):
return super().__new__(cls, (5, 3), **kwargs)
def __init__(self, **kwargs):
self[...] = -1
self.attrib = 0
def add2getstate(self):
print("add2getstate()", self.__dict__)
def __getstate__(self): # This never gets called
print("__getstate__()")
return super().__getstate__()
def __setstate__(self, data):
print("__setstate__()")
super().__setstate__(data)
if __name__ == "__main__":
fname = "fname.pkl"
x = Xndarray()
x[0] = 0
x.attrib += 2
print(x)
x.add2getstate()
print(x.attrib)
with open(fname, "wb") as fh:
pickle.dump(x, fh)
print("---------------")
with open(fname, "rb") as fh:
y = pickle.load(fh)
print(y)
y.add2getstate()
print(y.attrib)
这是输出:
[[ 0. 0. 0.]
[-1. -1. -1.]
[-1. -1. -1.]
[-1. -1. -1.]
[-1. -1. -1.]]
add2getstate() {'attrib': 2}
2
---------------
__setstate__()
[[ 0. 0. 0.]
[-1. -1. -1.]
[-1. -1. -1.]
[-1. -1. -1.]
[-1. -1. -1.]]
add2getstate() {}
Traceback (most recent call last):
File "./t.py", line 48, in <module>
print(y.attrib)
AttributeError: 'Xndarray' object has no attribute 'attrib'
【问题讨论】:
-
我有与 numpy 数组相关的其他属性,我希望将这些属性与 numpy 数组一起保存。此外,numpy 数组是更大的序列化数据结构的一部分。
标签: python numpy multidimensional-array pickle