首页 > 解决方案 > 将 dict 读入 self

问题描述

我有一堂课正在做很多事情。最后,它将所有内容保存到泡菜中。当我重新运行这门课时,我想阅读泡菜而不是再次做所有事情。不幸的是,如果我解开,变量总是空的。为什么呢?

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)

在这种情况下,如果我从泡菜中读取,变量是空的,但如果我做了所有的事情,那就是正确的......

标签: pythonclassdictionarypickle

解决方案


如果我想缓存一些计算结果,我将在类外加载/转储对象,例如,

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

推荐阅读