我有一个类,它正在做很多事情。最后,一切都陷入了困境。当我重新运行这个类时,我希望读取pickle,而不是再次执行所有操作。不幸的是,如果我解pickle,变量总是空的。为什么会这样呢?
import pandas as pd
class Test:
def __init__(path, value):
# path points to a .txt file but its in the same folder as the pickle
data_path, data = os.path.split(path)
pickle_path = os.path.join(data_path, name.split('.')[1] + '.pickle'
if os.path.isfile(pickle_path):
self = pd.read_pickle(path)
else:
# do a ton of stuff and safe it as pickle afterwards
variable = Test(path, value)
在这种情况下,如果我从pickle中读取,变量是空的但如果我执行所有操作,变量是正确的…
如果我想缓存一些计算结果,我将在类外加载/转储对象,如
pickle_path = os.path.join(data_path, name.split('.')[1] + '.pickle'
if os.path.isfile(pickle_path):
with open(pickle_path, 'rb') as f:
variable = pickle.load(f) # use cached results
else:
variable = Test() # do all the calculations