python - 将 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)
在这种情况下,如果我从泡菜中读取,变量是空的,但如果我做了所有的事情,那就是正确的......
解决方案
如果我想缓存一些计算结果,我将在类外加载/转储对象,例如,
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
推荐阅读
- elasticsearch - NEST elasticsearch POCO 的 ID 属性未设置
- python - matplotlib max_open_warning 数据过载
- android - 具有不同细节的可扩展 RecyclerView
- elasticsearch - 我在 logstash conf 文件的 sql_last_value 字段中不断收到值 0。有什么问题?
- node.js - 如果条件在 mjml 版本 3.3.5 中不起作用
- ruby-on-rails - ActiveStorage - 检索文件 URL
- perl - 使用“require”进行输出重定向
- c++ - 作为成员变量的 lambda 函数崩溃
- node.js - 硒验证文本框区域颜色
- javascript - 如何使用选项值禁用文本框