[英]Python pickle instance variables
我正在對一個實例變量進行一些計算,然后完成此操作,我想使該類實例腌制,這樣我就不必再次進行計算。 這里是一個例子:
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'}
我以為那會被腌制。 然而,
當我去加載類實例時:
import cPickle as pickle
from pickle_class_object import Test
t2 = pickle.load(open('test_file.pkl', 'rb'))
我在外殼中看到了這一點:
calculating c...
這意味着我沒有腌制c
,而是在重新計算。
有沒有一種方法來腌制test
我怎么想? 因此,我不必再次計算c
。 我看到我可以腌制test.__dict__
,但是我想知道是否有更好的解決方案。 另外,我對這里發生的事情的了解很薄弱,因此任何有關正在發生的事情的評論都會很棒。 我已經讀過有關__getstate__
和__setstate__
,但是我在這里看不到如何應用它們。
您將再次導入pickle_class_object
模塊,Python將運行該模塊中的所有代碼。
您的頂級模塊代碼包括對.compute()
調用。
您可能需要將創建泡菜的代碼移出模塊,或將其移至if __name__ == '__main__':
保護的部分:
if __name__ == '__main__':
test = Test(10, 'hello')
test.compute(6)
pickle.dump(test, open('test_file.pkl', 'wb'))
僅當運行python文件作為主腳本時, __name__
設置為__main__
; 當作為模塊導入時,將__name__
設置為模塊名稱,並且if
分支不會運行。
酸洗的工作原理與您預期的一樣。 這里的問題是,當您運行新腳本時,您將導入包含類Test
的模塊。 整個模塊都在運行,包括您創建test
。
處理此類問題的典型方法是在if __name__ == "__main__:
塊中保護這些內容。
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
if __name__ == "__main__":
import cPickle as pickle
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'))
那不是正在發生的事情。 您導入的是其中包含代碼的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 ...”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.