使用__setstate__和__getstate__的简单示例

时间:2009-12-21 09:17:07

标签: python serialization

我不知道__setstate____getstate__方法的作用,所以请帮我一个简单的例子。

4 个答案:

答案 0 :(得分:52)

这是Python 2的一个非常简单的示例,它应该补充pickle docs

class Foo(object):
  def __init__(self, val=2):
     self.val = val
  def __getstate__(self):
     print "I'm being pickled"
     self.val *= 2
     return self.__dict__
  def __setstate__(self, d):
     print "I'm being unpickled with these values:", d
     self.__dict__ = d
     self.val *= 3

import pickle
f = Foo()
f_string = pickle.dumps(f)
f_new = pickle.loads(f_string)

答案 1 :(得分:22)

最小例子

无论getstate出现什么,都会进入setstate。它不需要是一个字典。

getstate发出的任何内容都必须是可视的,例如由基本的内置插件组成,例如intstrlist

class C(object):
    def __init__(self, i):
        self.i = i
    def __getstate__(self):
        return self.i
    def __setstate__(self, i):
        self.i = i
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

默认__setstate__

默认__setstate__需要dict

self.__dict__https://stackoverflow.com/a/1939384/895245中的一个不错的选择,但我们可以自己构建一个以更好地了解正在发生的事情:

class C(object):
    def __init__(self, i):
        self.i = i
    def __getstate__(self):
        return {'i': self.i}
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

默认__getstate__

类似于__setstate__

class C(object):
    def __init__(self, i):
        self.i = i
    def __setstate__(self, d):
        self.i = d['i']
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

__slots__个对象没有__dict__

如果对象有__slots__,则它没有__dict__

如果您要同时实施getsetstate,默认方式是:

class C(object):
    __slots__ = 'i'
    def __init__(self, i):
        self.i = i
    def __getsate__(self):
        return { slot: getattr(self, slot) for slot in self.__slots__ }
    def __setsate__(self, d):
        for slot in d:
            setattr(self, slot, d[slot])
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

__slots__默认get和set需要一个元组

如果您想重复使用默认的__getstate____setstate__,则必须将元组传递为:

class C(object):
    __slots__ = 'i'
    def __init__(self, i):
        self.i = i
    def __getsate__(self):
        return (None, { slot: getattr(self, slot) for slot in self.__slots__ })
assert pickle.loads(pickle.dumps(C(1), -1)).i == 1

我不确定这是为了什么。

<强>继承

首先看到酸洗工作默认情况下:

class C(object):
    def __init__(self, i):
        self.i = i
class D(C):
    def __init__(self, i, j):
        super(D, self).__init__(i)
        self.j = j
d = pickle.loads(pickle.dumps(D(1, 2), -1))
assert d.i == 1
assert d.j == 2

继承自定义__getstate__

没有__slots__这很容易,因为__dict__的{​​{1}}包含D的{​​{1}},所以我们不需要触及{{} 1}}:

__dict__

继承和C

使用C,我们需要转发到基类,并且可以传递元组:

class C(object):
    def __init__(self, i):
        self.i = i
class D(C):
    def __init__(self, i, j):
        super(D, self).__init__(i)
        self.j = j
    def __getstate__(self):
        return self.__dict__
    def __setstate__(self, d):
        self.__dict__ = d
d = pickle.loads(pickle.dumps(D(1, 2), -1))
assert d.i == 1
assert d.j == 2

不幸的是,无法重用基数的默认__slots____slots__https://groups.google.com/forum/#!topic/python-ideas/QkvOwa1-pHQ我们被迫定义它们。

在Python 2.7.12上测试过。 GitHub upstream

答案 2 :(得分:4)

这些方法用于控制pickle模块对对象进行pickle和unpickled的方式。这通常是自动处理的,因此除非您需要覆盖类的pickle或unpickled方式,否则您不必担心它。

答案 3 :(得分:2)

对@BrainCore 的回答的澄清。在实践中,您可能不想修改 self 内的 __getstate__。而是构造一个将被腌制的新对象,保持原始对象不变以供进一步使用。效果如下:

import pickle

class Foo:
    def __init__(self, x:int=2, y:int=3):
        self.x = x
        self.y = y
        self.z = x*y

    def __getstate__(self):
        # Create a copy of __dict__ to modify values and return;
        # you could also construct a new dict (or other object) manually
        out = self.__dict__.copy()
        out["x"] *= 3
        out["y"] *= 10
        # You can remove attributes, but note they will not get set with
        # some default value in __setstate__ automatically; you would need
        # to write a custom __setstate__ method yourself; this might be
        # useful if you have unpicklable objects that need removing, or perhaps
        # an external resource that can be reloaded in __setstate__ instead of
        # pickling inside the stream
        del out["z"]
        return out

    # The default __setstate__ will update Foo's __dict__;
    # so no need for a custom implementation here if __getstate__ returns a dict;
    # Be aware that __init__ is not called by default; Foo.__new__ gets called,
    # and the empty object is modified by __setstate__

f = Foo()
f_str = pickle.dumps(f)
f2 = pickle.loads(f_str)

print("Pre-pickle:", f.x, f.y, hasattr(f,"z"))
print("Post-pickle:", f2.x, f2.y, hasattr(f2,"z"))