在存儲數據或者網絡傳輸數據的時候,須要對對象進行處理。把對象處理成方便存儲和傳輸的數據格式。這個過程叫序列化。python
不一樣的序列化,結果也不一樣,但目的是同樣的。都是爲了存儲和傳輸。redis
在python中存在三種序列化的方案:數據庫
把python對象寫入到文件中的一種解決方案,但寫入到文件的是bytes.json
將python對象序列化爲bytes類型後端
import pickle class Cat(object): def __init__(self, name, age): self.name = name self.age = age def eat(self): print("%s抓老鼠" % self.name) c = Cat("jerry", 5) bs = pickle.dumps(c) print(bs) # 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\x05ub.'
將bytes反序列化爲python對象。注:反序列化爲對象後,對象定義代碼必須存在,不然沒法使用對象網絡
import pickle class Cat(object): def __init__(self, name, age): self.name = name self.age = age def eat(self): print("%s抓老鼠" % self.name) bs = 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\x05ub.' cc = pickle.loads(bs) print(cc.name, cc.age) # jerry 5
import pickle class Person(object): def __init__(self, name, pwd): self.name = name self.pwd = pwd lst = [Person("Tom", "123"), Person("Linda", "123"), Person("john", "123")] # 寫 with open("login", mode="wb") as f: for el in lst: pickle.dump(el, f) # 讀 with open("login", mode="rb") as f: for i in range(len(lst)): # 已知對象個數,對文件進行遍歷讀取 ret = pickle.load(f) print(ret.name, ret.pwd) 結果: Tom 123 Linda 123 john 123
import pickle class Cat(object): def __init__(self, name, age): self.name = name self.age = age def eat(self): print("%s抓老鼠" % self.name) lst = [Cat("jerry", 5), Cat("tomy", 6), Cat("alpha", 7)] with open("cat", mode="wb") as f: pickle.dump(lst, f) with open("cat", mode="rb") as f: ret = pickle.load(f) for el in ret: el.eat() 結果: jerry抓老鼠 tomy抓老鼠 alpha抓老鼠
註冊登陸程序spa
import pickle class User(object): def __init__(self, username, password): self.username = username self.password = password class Client(object): def regist(self): uname = input("username: ") pwd = input("password: ") user = User(uname, pwd) pickle.dump(user, open("userinfo", mode="wb")) print("regist successful!") def login(self): uname = input("username: ") pwd = input("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 def run(self): self.regist() self.regist() self.login() if __name__ == "__main__": c = Client() c.run()