pickle⽤起来很简单. 说⽩了. 就是把我们的python对象写入到⽂件中的⼀种解决方案.
但是写入到⽂件的是bytes. 所以这东⻄不是给人看的. 是给机器看的.
import pickle
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def catchMouse(self):
print(self.name, "抓老鼠")
c = Cat("jerry", 18)
bs = pickle.dumps(c) # 序列化⼀个对象.
print(bs) # ⼀堆⼆进制. 看不懂
能不能将类干掉呢?
import pickle
将类注释掉
# class Cat:
# def __init__(self, name, age):
# = name
# self.age = age
#
# def catchMouse(self):
# print(self.name, "抓老鼠")
# c = Cat("jerry", 18)
#
# bs = pickle.dumps(c) # 序列化⼀个对象.
# print(bs) # ⼀堆⼆进制. 看不懂
cc = pickle.loads(b'\x80\x03c__main__\nCat\nq\x00)\x81q\x01}q\x02(X\x04\x00\x00\x00nameq\x03X\x05\x00\x00\x00jerryq\x04X\x03\x00\x00\x00ageq\x05K\x12ub.') # 把⼆进制反序列化成我们的对象
print(cc)
cc.catchMouse()
结果:报错
不能将类给去掉,因为pickle.dumps是序列化一个对象,而不是一个类,所以可以将对象c = Cat("jerry", 18) 注释掉,而不能将类class Cat:注释掉
pickle中的dumps可以序列化⼀个对象. loads可以反序列化⼀个对象. 我们使用dump还可以直接把一个对象写入到⽂件中
# f = open("cat", mode="wb") #要用wb因为是写入bit文件
# pickle.dump(c, f) # 写入到⽂件中
# f.close()
f = open("cat", mode="rb") #rb读取bit文件
cc = pickle.load(f) #从⽂件中读取对象
cc.catchMouse() #要保证代码中要有类才能读取对象
pickle还⽀持多个对象的写出.
import pickle
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def catchMouse(self):
print(self.name, "抓老鼠")
lst = [Cat("jerry", 19), Cat("tommy", 20), Cat("alpha", 21)] #放入3个对象
f = open("cat", mode="wb")
for el in lst:
pickle.dump(el, f) # 写⼊到文件中
f.close()
f = open("cat", mode="rb")
for i in range(len(lst)):
cc = pickle.load(f) # 从⽂件中读取对象
cc.catchMouse()
结果:
jerry 抓老鼠
tommy 抓老鼠
alpha 抓老鼠
但是这样写并不够好. 因为读的时候. 并不能知道有多少对象要读.这里记住,不能一行一行的读。那真的要写入或者读取多个内容怎么办?
很简单.装list里。然后读取和写入都用list
lst = [Cat("jerry", 19), Cat("tommy", 20), Cat("alpha", 21)] #放入3个对象
f = open("cat", mode="wb")
pickle.dump(lst, f) # 写⼊到文件中
f.close()
f = open("cat", mode="rb")
ll = pickle.load(f)
for el in ll:
el.catchMouse()
注册系统
import pickle
class User:
def __init__(self,username,password):
self.username = username
self.password = password
class client:
def regist(self):
uname = input("please input your name:")
pwd = input("please input your password:")
user = User(uname,pwd) #制造对象
pickle.dump(user,open("userinfo",mode="ab")) #将对象写入userinfo
print("regist successful!!!")
def login(self):
uname = input("please input your name:")
pwd = input("please input your password:")
f = open("userinfo",mode="rb")
while 1:
try:
u = pickle.load(f)
if u.username == uname and u.password == pwd:
print("login successful")
break
except Exception as e:
print("login failed !!!")
break
c = client()
c.regist() #注册
c.login() #登陆