Python,override__getstate __()和__setstate __()

时间:2012-09-27 18:35:17

标签: python

我有这些课程:

class Family(object):
    __slot__ = ['father', 'var1']
    def __init__(self, father, var1 = 1):
        self.father, self.var1 = father var1

class Father(object):
    __slots__ = ['var2']
    def __init__(self, var2 = ''):
        self.var2 = var2

father = Father()
family = Family(father = father)

我想腌制“家庭”对象。所以我需要覆盖__getstate____setstate__ “家庭”和“父亲”课程。

你能告诉我一个有效的方法吗? (我使用__slots__的原因是因为我有很多对象,而我正试图节省内存)

1 个答案:

答案 0 :(得分:22)

__getstate__应该返回一个可选对象(例如元组),其中包含足够的信息来重构实例。

__setstate__应该期望接收相同的对象,并使用它来重新配置实例。

例如:

import cPickle as pickle

class Family(object):
    __slots__ = ['father', 'var1']
    def __init__(self, father, var1 = 1):
        self.father, self.var1 = father, var1
    def __getstate__(self):
        return self.father, self.var1
    def __setstate__(self, state):
        self.father, self.var1 = state

foo = Family('father',1)
foo.var1 = 2
foo_pickled = pickle.dumps(foo)
foo2 = pickle.loads(foo_pickled)
print(repr(foo2))
# <__main__.Family object at 0xb77037ec>

print(foo2.var1)
# 2