Python pickle模块

Posted on 2018-12-29 17:09  缥缈映苍穹  阅读(214)  评论(0)    收藏  举报
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'\x80\x03c__main__\nElephant\nq\x00)\x81q\x01}q\x02(X\x04\x00\x00\x00nameq\x03X\x06\x00\x00\x00\xe5\xae\x9d\xe5\xae\x9dq\x04X\x06\x00\x00\x00weightq\x05X\x04\x00\x00\x00185Tq\x06X\x06\x00\x00\x00heightq\x07X\x03\x00\x00\x00175q\x08ub.'
# 发序列化
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()