Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-保存整个类对象(大型属性除外)_Python_Python 2.7_Serialization_Python 3.x_Save - Fatal编程技术网

Python-保存整个类对象(大型属性除外)

Python-保存整个类对象(大型属性除外),python,python-2.7,serialization,python-3.x,save,Python,Python 2.7,Serialization,Python 3.x,Save,我有一个我想保存的对象,但它的一个属性非常大,不需要保存。除了一个属性外,如何保存对象。下面是我目前的解决方案 class Example(object): def __init__(self): self.attribute_one = 1 self.attribute_two = 'blah blah' ... self.attribute_large = very_large_object save_this_exc

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

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() 
一个可能的解决办法是

def save_example(example):
    save_this = copy.deepcopy(example)
    save_this.attribute_large = None
    pickle.dump(save_this,open('save_path','w'))
除了上面的解决方案没有内存效率,因为在将其中一个设置为“无”之前,内存中将有2个属性_大


任何建议

您都可以使用dict comprehension来构建一个新的dict来进行pickle,省去大属性:

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

使用
\uuuu getstate\uuuuuuuuuu
/
\uuuuu setstate\uuuuuuuuuu
允许实际进行酸洗的代码不必担心
示例的实现细节;它只是对对象进行pickle处理,而对象本身做了正确的事情。

您使用的是名为
deep
的模块吗?PyPI上的文件似乎没有
copy()
。或者你正在使用copy.deepcopy()
?哎呀,那是个打字错误,意思是copy.deepcopy()