Discuss / Python / 交作业

交作业

Topic source
#序列化 反序列化
import pickle

d = dict(name = 'cuish', age = 30, score = 98)
pickle.dumps(d)

strfile = 'f:\\python\\project\\40.txt'
f = open(strfile, 'wb')
pickle.dump(d, f)
f.close()


f = open(strfile, 'rb')
d = pickle.load(f)
f.close()
print (d)


########### json #############
import json

d = dict(name = 'cuish', age = 30, score = 98)
str = json.dumps(d)
print (str)

json_str = '{"age":28, "score":100, "name":"cgf"}'
json.loads(json_str)

####################### json improve #########
class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

def student2dict(stud):
    return {
        'name':stud.name,
        'age': stud.age,
        'score': stud.score
    }

s = Student('cgf', 25, 97)
print (json.dumps(s, default = student2dict))
print (json.dumps(s, default = lambda obj : obj.__dict__))


def dict2student(d):
    return Student(d['name'], d['age'], d['score'])

json_str = '{"age":25, "name":"fgc", "score":98}'
print (json.loads(json_str, object_hook = dict2student))

输出

省略


  • 1

Reply