如何将python类的所有信息保存到二进制文件?

时间:2019-01-11 17:56:37

标签: python python-3.x serialization pickle

我正在创建一个小外壳应用程序,以帮助我保存一些信息并查看一些python。

对于一堆相互引用的类,我有一些python代码,例如User,Person,Contact,Event,然后是用于测试它的主要App.py。

我正在用泡菜保存数据,using this question as inspiration.

我的问题是,尽管该类已保存,但它是“内部信息不是”。

import Event
import Contact
import pickle
def saveObj(filename, obj):
    with open(filename, 'wb') as output:
    pickle.dump(obj,output, pickle.HIGHEST_PROTOCOL)
    print("SAVED")

def loadObj(filename, obj):
    with open(filename, 'rb') as input:
    obj = pickle.load(input)
    print("LOADED")

p1 = Person.Person("abcd",12,"ui")
p2 = Person.Person("Hah",123,"aaa")
c1 = Contact.Contact([p1,p2], "Wakanda", "12-23-54")
e1 = Event.Event([p1],"12-32-31")
e1.setTitle();
e1.setDescription();

c2 = Contact.Contact([p2],"Forever", "12-23-53")


print("1 for new user, 2 for existing user")
ipt = input("Write something but not exit!\n>>")
filename = ""
while (ipt!= "exit!"):
    if (ipt=="1"):
        print("1")
        idNumber = input("Insert id\n>> ")
        name = input("Inser name\n>> ")
        filename = str(idNumber)+".data"
        session = LoggedIn.User(idNumber,name)
        session.addStuff([e1],[c1,c2],[p1,p2])
        print(session.people)
        saveObj(filename,session)
        del session
    elif(ipt=="2"):
        print("2")
        session = LoggedIn.User(None,None)    
        loadObj(filename,session)
        print(session.people)
    ipt = input("Write something but not exit!\n>>")

我想要的回报等于使用选项 1 和选项 2 时的回报。而是这样:

1 for new user, 2 for existing user
Write something but not exit!
>>1
1
Insert id
>> 12345678
Inser name
>> AAA
[<Person.Person object at 0x7fa8079c6908>, <Person.Person object at 0x7fa8079c6940>]
SAVED
Write something but not exit!
>>2
2
LOADED
[]
Write something but not exit!
>>

我该如何解决?

1 个答案:

答案 0 :(得分:1)

obj = pickle.load(input)不会更改您通过obj参数传入的对象的值。尝试使用return

def loadObj(filename):
    with open(filename, 'rb') as input:
        obj = pickle.load(input)
    print("LOADED")
    return obj

#later...

print("2")
session = loadObj(filename)
print(session.people)