Python - 保存除大属性外的整个类对象

Wil*_*amp 2 python serialization save python-2.7 python-3.x

我有一个我想保存的对象,但它的一个属性非常大,不需要保存。除了一个属性之外,我如何保存对象。以下是我目前的解决方案。

class Example(object):
    def __init__(self):
        self.attribute_one = 1
        self.attribute_two = 'blah blah'
        ...
        self.attribute_large = very_large_object

save_this_except_attribute_large = Example() 
Run Code Online (Sandbox Code Playgroud)

一种可能的解决方案是

def save_example(example):
    save_this = copy.deepcopy(example)
    save_this.attribute_large = None
    pickle.dump(save_this,open('save_path','w'))
Run Code Online (Sandbox Code Playgroud)

除了上述解决方案的内存效率不高,因为在我们将其中一个设置为 None 之前,我们将在内存中有 2 个 attribute_large。

有什么建议

dan*_*ano 5

您可以将 dict 理解与__getstate__/__setstate__一起使用来构建一个新的要腌制的 dict,而忽略 large 属性:

class Example(object):
    def __init__(self):
        self.attribute_one = 1
        self.attribute_two = 'blah blah'
        ...
        self.attribute_large = very_large_object

    def __getstate__(self):
        d = self.__dict__
        self_dict = {k : d[k] for k in d if k != 'attribute_large'}
        return self_dict

    def __setstate__(self, state):
        self.__dict__ = state
Run Code Online (Sandbox Code Playgroud)

使用__getstate__/__setstate__允许实际执行酸洗的代码不必担心Example; 它只是腌制对象,对象本身做正确的事情。