Skip to main content
 首页 » 编程设计

Python pickle 实例变量

2025年05月04日21qlqwjy

我正在对实例变量进行一些计算,完成后我想 pickle 类实例,这样我就不必再次进行计算。这里有一个例子:

import cPickle as pickle 
 
class Test(object): 
    def __init__(self, a, b): 
        self.a = a 
        self.b = b 
        self.c = None 
    def compute(self, x): 
        print 'calculating c...' 
        self.c = x * 2 
 
test = Test(10, 'hello') 
test.compute(6) 
 
# I have computed c and I want to store it, so I don't have to recompute it again: 
 
pickle.dump(test, open('test_file.pkl', 'wb')) 

在 test.compute(6) 之后,我可以查看 test.__dict__ 是什么:

>>> test.__dict__ 
{'a': 10, 'c': 12, 'b': 'hello'} 

我以为这就是要 pickle 的东西;然而,

当我去加载类实例时:

import cPickle as pickle 
 
from pickle_class_object import Test 
 
t2 = pickle.load(open('test_file.pkl', 'rb')) 

我在 shell 中看到了这个:

calculating c... 

这意味着我没有 pickle c 并且我正在重新计算它。

有没有办法按照我的意愿来 pickle test?所以我不必重新计算 c。我看到我可以 pickle test.__dict__,但我想知道是否有更好的解决方案。此外,我对这里发生的事情的理解很薄弱,所以任何关于正在发生的事情的评论都会很棒。我读过有关 __getstate__ 和 __setstate__ 的内容,但我不知道如何在此处应用它们。

请您参考如下方法:

您正在再次导入 pickle_class_object 模块,Python 运行该模块中的所有代码。

您的顶级模块代码包括对 .compute() 的调用,这就是被调用的内容。

您可能希望将创建 pickle 的代码移出 模块,或将其移至 if __name__ == '__main__': protected 部分:

if __name__ == '__main__': 
    test = Test(10, 'hello') 
    test.compute(6) 
 
    pickle.dump(test, open('test_file.pkl', 'wb')) 

仅当作为主脚本运行python文件时,__name__设置为__main__;当作为模块导入时,__name__ 设置为模块名称,if 分支将不会运行。