在程序生命周期的某个时刻创建了一个testclass
对象,然后使用pickle
或h5py
在文件系统中对其进行序列化。现在,在此期间,testclass
的定义已更新。更新始终是关于添加新字段(而不是删除现有字段)。
反序列化存储的类并使用更新的testclass
定义引用是正确的方法吗?
序列化之前:定义类
class testclass:
__fieldA = None
__fieldB = None
__fieldC = 'Hello'
def __init__(self, A, B):
self.__fieldA = A
self.__fieldB = B
def setA(self, A):
self.__fieldA = A
def getA(self):
return self.__fieldA
def setB(self, B):
self.__fieldB = B
def getB(self):
return self.__fieldB
def setC(self, C):
self.__fieldC = C
def getC(self):
return self.__fieldC
>>>orig_obj = testclass('testA', 'testB')
>>>isinstance(orig_obj, testclass)
>>>True
>>>with open('test', 'wb') as handle:
pickle.dump(orig_obj, handle, protocol=pickle.HIGHEST_PROTOCOL)
序列化之后:类定义已更改
class testclass:
__fieldA = None
__fieldB = None
__fieldC = 'Hello'
__fieldD = 10
def __init__(self, A, B):
self.__fieldA = A
self.__fieldB = B
def setA(self, A):
self.__fieldA = A
def getA(self):
return self.__fieldA
def setB(self, B):
self.__fieldB = B
def getB(self):
return self.__fieldB
def setC(self, C):
self.__fieldC = C
def getC(self):
return self.__fieldC
def setD(self, D):
self.__fieldD = D
def getD(self):
return self.__fieldD
>>>with open('test', 'rb') as handle:
loaded_obj = pickle.load(handle)
>>>isinstance(loaded_obj, testclass)
>>>False
现在loaded_obj
不是testclass
的实例。这是有道理的,与是否引入新字段__fieldD
无关。
在这种情况下,确保loaded_obj
是testclass
的实例的最佳方法是什么?