序列化和反序列化之间的基础类更改

时间:2019-02-27 19:57:45

标签: python-2.7 serialization pickle

在程序生命周期的某个时刻创建了一个testclass对象,然后使用pickleh5py在文件系统中对其进行序列化。现在,在此期间,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_objtestclass的实例的最佳方法是什么?

0 个答案:

没有答案