gpt4 book ai didi

python - 使用 pickle 或 dill 保存类数据不起作用

转载 作者:行者123 更新时间:2023-12-01 08:39:03 26 4
gpt4 key购买 nike

我想将 poll 类数据的状态保存到文件中,如果我的脚本重新启动,则将其加载回来。我弹出了部分程序来重现该问题。这是我的文件。

pickleclass.py

#POLL RECORD
class POLL:
title = ''
votes = {}
duration = 0
secenekler = 0
sure = ""
polltype = -1 # -1 initial, 0 = %, 1 = Sayi
chat_id = None
message_id = None

def reset():
POLL.title = ''
POLL.votes.clear()
POLL.duration = 0
POLL.secenekler = 0
POLL.sure = ""
POLL.polltype = -1
POLL.chat_id = None
POLL.message_id = None

fxns.py

def save_to_file(obj, filename):
"""
Saves obj to file named with fn as pickly object.
"""
import pickle
with open(filename, 'wb') as output: # Overwrites any existing file.
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)


def load_from_file(fn):
import pickle
"""
reads from file given in fn and returns object of dump pickle file
"""
return pickle.load( open( fn, "rb" ) )

保存.py

import pickleclass as pk
import fxns as fxn
Poll_file = "p.dump"

poll = pk.POLL

poll.title = "TEST TITLE"
poll.votes['VOTE 1'] = 1
poll.votes['VOTE 2'] = 2
poll.votes['VOTE 3'] = 3

poll.duration = 0.4
poll.secenekler = 1
poll.sure = "23:55"
poll.polltype = 1
poll.chat_id = 112431
poll.message_id = 324

print("-"*55)
print("-"*55)
bozo = vars(poll)
for key in bozo.keys():
print(key, "=", bozo[key])

print("-"*55)
fxn.save_to_file(poll, Poll_file)

首先,我调用 save.py 创建类,然后保存它。其成功结束。在 save.py 脚本之后,我在下面调用 load.py 来加载保存的内容。但它加载空类数据。因为它是新创建的。save.py文件的输出如下:

('reset', '=', <function reset at 0x7f4485277758>)
('__module__', '=', 'pickleclass')
('sure', '=', '23:55')
('secenekler', '=', 1)
('title', '=', 'TEST TITLE')
('__doc__', '=', None)
('votes', '=', {'VOTE 2': 2, 'VOTE 3': 3, 'VOTE 1': 1})
('polltype', '=', 1)
('chat_id', '=', 112431)
('duration', '=', 0.4)
('message_id', '=', 324)

load.py

import pickleclass as pk
import fxns as fxn
Poll_file = "p.dump"

zozo = fxn.load_from_file(Poll_file)
zozo = vars(zozo)

for key in zozo.keys():
print(key, "=", zozo[key])
print("-"*55)
print("-"*55)

当我加载文件并显示输出时,它是空的,如下所示。

('reset', '=', <function reset at 0x7f8e99907758>)
('__module__', '=', 'pickleclass')
('sure', '=', '')
('secenekler', '=', 0)
('title', '=', '')
('__doc__', '=', None)
('votes', '=', {})
('polltype', '=', -1)
('chat_id', '=', None)
('duration', '=', 0)
('message_id', '=', None)

我找不到问题所在。它加载类但不加载数据。

最佳答案

加载已正确执行:问题来自于您的类未正确实现。

看看some material on classes and instances (或一些帖子 on SO ),特别是 __init__ 函数、self 以及实例和类成员等概念(另请参阅 that post 中密切相关的问题)。

那就看怎么pickle处理类(class),你应该可以开始了。

编辑显然使用dill这实际上应该是可能的,请参阅this SO post

关于python - 使用 pickle 或 dill 保存类数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53574082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com