我正在尝试创建一个可以使用类方法序列化和反序列化自身的对象,而不使用 return 语句(我不想要静态方法)。这是我的班级的一个概念和一个天真的用例:
import pickle
class A:
def __init__(self):
self.x = 0
def add(self):
self.x += 1
def serialize(self, filename):
"""Simple object serialization given a filename"""
with open(filename, 'wb') as f:
pickle.dump(self, 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 = pickle.load(f)
print("Deserialized value inside deserialize function: %d" % (self.x))
a1 = A()
a2 = A()
a1.add()
a1.add()
a1.serialize('a.pkl')
a2.deserialize('a.pkl')
print("Deserialized value outside: %d" % (a2.x))
但是,一旦我离开反序列化方法,self(在这种情况下,实例a2)就不会保留其值。
运行时输出:
>> Serialized with value of: 2
>> self.x before load (inside deserialize): 0
>> Deserialized value inside deserialize function: 2
>> Deserialized value outside: 0
为什么会这样?我也尝试过在函数deepcopy之后使用pickle.load,deserialize但似乎没有任何效果,我想了解原因。
收到一只叮咚
HUWWW
相关分类