【发布时间】:2014-08-13 16:48:08
【问题描述】:
我有一个要保存的对象,但其中一个属性非常大,不需要保存。除了那个属性,我如何保存对象。以下是我目前的解决方案。
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'))
除了上述解决方案的内存效率不高,因为在我们将其中一个设置为 None 之前,我们将在内存中有 2 个 attribute_large。
任何建议
【问题讨论】:
-
您是否在使用名为
deep的模块? PyPI 上的那个似乎没有copy()。还是您使用copy.deepcopy()? -
哎呀,这是一个错字,意思是 copy.deepcopy()
标签: python python-2.7 serialization python-3.x save