2 回答
TA贡献1821条经验 获得超4个赞
这不起作用的原因是因为你不能分配给 self (或者更确切地说:这样做并没有做你认为它做的事情)。如果您有兴趣了解实际发生的情况,请尝试为 分配一些奇怪的东西self,例如self = "foobar"(行为将保持不变)。
制作deserialize一个类方法并将其用作“构造函数”:
@classmethod
def deserialize(cls, filename):
"""Simple object deserialization given a filename"""
with open(filename, 'rb') as f:
obj = pickle.load(f)
print("Deserialized value inside deserialize function: %d" % (obj.x))
return obj
然后像这样使用它:
a2 = A.deserialize('a.pkl')
输出:
序列化值:2
反序列化函数内部反序列
化值:2 外部反序列化值:2
TA贡献1874条经验 获得超12个赞
回复晚了非常抱歉。Pickle 将对象扁平化为字典。这是修复它的方法:
def serialize(self, filename):
"""Simple object serialization given a filename"""
with open(filename, 'wb') as f:
pickle.dump(self.__dict__, f)
print("Serialized with value of: %d" % (self.x))
def deserialize(self, filename):
"""Simple object deserialization given a filename"""
with open(filename, 'rb') as f:
print("self.x before load (inside deserialize): %d" % (self.x))
self.__dict__ = pickle.load(f)
print("Deserialized value inside deserialize function: %d" % (self.x))
添加回答
举报