-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy path34_pickle.py
More file actions
39 lines (29 loc) · 938 Bytes
/
34_pickle.py
File metadata and controls
39 lines (29 loc) · 938 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
__author__ = 'Admin'
# pickle 实现序列化 使用方法dumps
# import pickle
#
# d = dict(name='Bob', age=20, score=88)
# data = pickle.dumps(d)
# print(data)
#
# reborn = pickle.loads(data)
# print(reborn)
import json
d = dict(name='Bob', age=20, score=88)
data = json.dumps(d)
print('JSON Data is a str:', data)
reborn = json.loads(data)
print(reborn)
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def __str__(self):
return 'Student object (%s, %s, %s)' % (self.name, self.age, self.score)
s = Student('Bob', 20, 88)
#通常class的实例都有一个__dict__属性,它就是一个dict,用来存储实例变量
std_data = json.dumps(s, default=lambda obj: obj.__dict__)
print('Dump Student:', std_data)
rebuild = json.loads(std_data, object_hook=lambda d: Student(d['name'], d['age'], d['score']))
print(rebuild)