python中的类方法中的自我解开

时间:2018-10-17 11:25:41

标签: python deserialization self

我试图创建一个对象,该对象可以使用类方法进行序列化和反序列化,而无需使用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

为什么会这样?我还在功能deepcopypickle.load之后尝试过deserialize,但似乎没有任何作用,我想理解为什么。

预先感谢

2 个答案:

答案 0 :(得分:1)

之所以不起作用,是因为您无法分配给自己(或者说:这样做不符合您的想法)。如果您想了解实际发生的情况,请尝试为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

答案 1 :(得分:1)

对不起,您的回复很晚。 泡菜将对象扁平化为字典。 解决方法如下:

    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))