1. 作用
用于存储和运输。将内存中的变量存入硬盘
2. 操作
# 序列化
import pickle
# 字典变量
dic = dict(nane='Bob', age=20, score=88)
print(dic)
p = pickle.dumps(dic)
print(p)
d = pickle.loads(p)
print(d)
# 函数
def love_me_as_i_go():
print('爱我就跟我走')
love = love_me_as_i_go
print(love)
p = pickle.dumps(love)
print(p)
love = pickle.loads(p)
print(love)
love()
# 保存在文件中
f = open('dump.txt', 'wb')
pickle.dump(love, f)
f.close()
# 在文件中取出来
f = open('dump.txt', 'rb')
love = pickle.load(f)
f.close()
love()
# JSON 最流行的编码格式
import json
d = dict(name='Bob', age=20, score=88)
j = json.dumps(d)
print(j)
d = json.loads(j)
print(d)
class User(object):
def __init__(self, id, name, password):
self.id = id
self.name = name
self.password = password
s = User(1, 'Tommy', 'TommyLoveLauUser')
# print(json.dumps(s))
# TypeError: <__main__.User object at 0x10603cc50> is not JSON serializable
# User不是一个序列化对象
print(json.dumps(s, default=lambda obj: obj.__dict__))
def object_to_json(user):
return {'id': user.id, 'name': user.name, 'password': user.password}
print(json.dumps(s, default=object_to_json))
def json_to_object(obje):
return User(obje['id'], obje['name'], obje['password'])
网友评论