使用dill保存类变量更改

时间:2017-12-04 19:48:28

标签: python-3.x tkinter pickle dill

我用tkinter编写了一个使用类作为结构的应用程序。目前我尝试实现" save" -function,以便可以关闭应用程序,如果它重新启动,则决定是从头开始还是使用已经存在的aka。腌制数据。

我读到了pickle-module及其无法保存类变量的弱点,所以我决定使用dill-module代替。

我的问题:dill保存了我的类变量的起始值,但是如果我让用户更改类变量(通过调用classmethods),则不会保存更改。有没有办法用腌渍或莳萝模块做到这一点?

我创建了一个产生错误的最小示例。您可以看到,即使在调用更改变量的实例方法之后,也会保存实例变量的更改。不幸的是,它不适用于类变量及其相应的类方法:

import dill as pickle
from tkinter import *

root = Tk()

# creating class
class Roomie:

    # class variable: total number of expenses
    num_exp = 0

    # init method: every roomie has a name, info for each expense, etc...
    def __init__(self,fname,exp=0.00):

        self.fname = fname
        self.exp = exp

    def raiseExp(self):
        self.exp += 1

    # class method: every time someone spend smth value of class variable num_exp increases by one
    @classmethod
    def updateExpNum(cls):
        cls.num_exp += 1

# saving instance of class in list object
roomie_0 = Roomie("Cthulhu")
roomie_list = [roomie_0]


def pickleRoomies():

    file_Name = "debts.pkl"
    # open file for writing
    fileObject = open(file_Name,'wb') 
    # write roomie_list to file
    pickle.dump(roomie_list,fileObject)   
    # here we close the fileObject
    fileObject.close()

# load all instances and class variables
def loadPickle():

    global roomie_list

    filepath = "debts.pkl"

    file = open(filepath, "rb" )

    roomie_list = pickle.load(file)

# create buttons and bind instance and class methods to them
button_0 = Button(root,text="update number of expenses",command=lambda: Roomie.updateExpNum())
button_1 = Button(root,text="raise expense",command=lambda: roomie_list[0].raiseExp())
button_2 = Button(root,text="save changes",command=lambda: pickleRoomies())
button_3 = Button(root,text="load changes",command=lambda: loadPickle())

button_0.pack()
button_1.pack()
button_2.pack()
button_3.pack()

# run GUI
root.mainloop()


# check program

# print instance variable
print("total expenses:",roomie_list[0].exp)
# print class variable
print("number of expenses:", Roomie.num_exp)
# print instance variable
print("name:", roomie_list[0].fname)

0 个答案:

没有答案