Python pickle实例变量
我正在对一个实例变量进行一些计算,然后我想对类实例进行pickle,这样我就不必再进行计算了。这里有一个例子:Python pickle实例变量,python,pickle,Python,Pickle,我正在对一个实例变量进行一些计算,然后我想对类实例进行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...'
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.compute6之后,我可以检查一下什么是测试
我以为这就是要被腌制的东西;但是,
当我去加载类实例时:
import cPickle as pickle
from pickle_class_object import Test
t2 = pickle.load(open('test_file.pkl', 'rb'))
我在shell中看到了这一点:
calculating c...
这意味着我没有对c进行pickle,我正在重新计算它
有没有一种方法可以验证我的想法?所以我不必再次计算c。我知道我可以做个泡菜测试。但我想知道是否有更好的解决方案。另外,我对这里发生的事情的理解很弱,所以任何关于发生的事情的评论都是很好的。我读过关于uuu getstate和uu setstate的文章,但我不知道如何在这里应用它们。酸洗的效果与您预期的一样。这里的问题是,当您运行新脚本时,您将导入包含类测试的模块。运行整个模块,包括创建测试的位 处理这类事情的典型方法是在if\uuuu name\uuuuu==\uuuuuu main\uuuuu:块中保护内容
酸洗的效果和你期望的一样。这里的问题是,当您运行新脚本时,您将导入包含类测试的模块。运行整个模块,包括创建测试的位 处理这类事情的典型方法是在if\uuuu name\uuuuu==\uuuuuu main\uuuuu:块中保护内容 再次导入pickle_class_对象模块,Python将运行该模块中的所有代码 您的顶级模块代码包括对.compute的调用,这就是所调用的 您可能希望将创建pickle的代码移出模块,或将其移动到if _uname_uu=='_u main_uuu':受保护的部分:
if __name__ == '__main__':
test = Test(10, 'hello')
test.compute(6)
pickle.dump(test, open('test_file.pkl', 'wb'))
仅当作为主脚本运行python文件时,才将_uname_;设置为_umain_;;作为模块导入时,名称改为模块名称,if分支将不会运行。您再次导入pickle\u class\u对象模块,Python将运行该模块中的所有代码
您的顶级模块代码包括对.compute的调用,这就是所调用的
您可能希望将创建pickle的代码移出模块,或将其移动到if _uname_uu=='_u main_uuu':受保护的部分:
if __name__ == '__main__':
test = Test(10, 'hello')
test.compute(6)
pickle.dump(test, open('test_file.pkl', 'wb'))
仅当作为主脚本运行python文件时,才将_uname_;设置为_umain_;;作为模块导入时,名称改为模块名称,if分支将不会运行。实际情况并非如此。导入一个python模块,该模块在顶层包含代码,在导入模块时执行。您可以看到您的代码按预期工作:
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)
pickle.dump(test, open('test_file.pkl', 'wb'))
t2 = pickle.load(open('test_file.pkl', 'rb'))
print t2.c
--output:--
calculating c...
12
如果您的代码按照您描述的那样工作,那么您将看到计算c。。。两次。事情不是这样的。导入一个python模块,该模块在顶层包含代码,在导入模块时执行。您可以看到您的代码按预期工作:
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)
pickle.dump(test, open('test_file.pkl', 'wb'))
t2 = pickle.load(open('test_file.pkl', 'rb'))
print t2.c
--output:--
calculating c...
12
如果您的代码按照您描述的那样工作,那么您将看到计算c。。。两次