用 pickle 或 dill 保存 Class 数据不起作用

Saving Class data with pickle or dill doesn't work

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

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" ) )

save.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 创建 class 然后保存它。它成功结束。在 save.py 脚本之后,我在下面调用 load.py 来加载保存的内容。但它加载空 class 数据。因为它是新创建的。 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)

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

加载已正确执行:问题来自您的 class 未正确实施。

看看 some material on classes and instances (or some posts on SO), especially the __init__ function, self, and notions like instance and class members (see also a closely related problem in that post)。

然后看看 pickle 如何处理 classes,你应该可以开始了。

Edit 显然用 dill 这实际上应该是可能的,参见 this SO post