import pickle # class Elephant: def __init__(self, name, weight, height): self.name = name self.weight = weight self.height = height def tiaoxi(self): print(f"{self.name}大象特别喜欢调戏人") # e = Elephant("宝宝", "185T", "175") # e.tiaoxi() # # # 序列化 # bs = pickle.dumps(e) # 把对象进行序列化 # print(bs) # # bs = b'x80x03c__main__ Elephant qx00)x81qx01}qx02(Xx04x00x00x00nameqx03Xx06x00x00x00xe5xaex9dxe5xaex9dqx04Xx06x00x00x00weightqx05Xx04x00x00x00185Tqx06Xx06x00x00x00heightqx07Xx03x00x00x00175qx08ub.' # # 发序列化 # dx = pickle.loads(bs) # 发序列化. 得到的是大象 # dx.tiaoxi() # e1 = Elephant("宝宝", "185T", "175") # e2 = Elephant("宝贝", "120T", "120") # f = open("大象", mode="wb") # # 这也是序列化 # pickle.dump(e1, f) # 没有s的这个方法是把对象打散写入到文件, 序列化的内容不是给人看的 # pickle.dump(e2, f) # 没有s的这个方法是把对象打散写入到文件, 序列化的内容不是给人看的 # f = open("大象", mode="rb") # while 1: # try: # obj = pickle.load(f) # obj.tiaoxi() # except Exception: # break # e1 = Elephant("宝宝", "185T", "175") # e2 = Elephant("宝贝", "120T", "120") # lst = [e1, e2] # pickle.dump(lst, open("大象", mode="wb")) # 读 # lst = pickle.load(open("大象", mode="rb")) # for dx in lst: # dx.tiaoxi()