python中序列化对象

# 序列化对象p1

import pickle                               # 内置库

class People:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sayhi(self):
        print("Hi, my name is {}, and I'm {}".format(self.name, self.age))

p1 = People(name="Jack", age=30)

p1.sayhi()                                  # Hi, my name is Jack, and I'm 30

f = open('p1', 'wb')                        # 以二进制的方式
pickle.dump(p1, f)                          # 参数为python的对象和文件句柄

f.close()

这样写入python对象后,在程序目录下产生一个p1文件

下面我们来加载这个p1文件,从而使用p1这个对象对应的类中的属性

import pickle

class People:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sayhi(self):
        print("Hi, my name is {}, and I'm {}".format(self.name, self.age))


# 测试序列化对象的加载


f = open('p1', 'rb')                        # 用二进制的方式读
p2 = pickle.load(f)                         # 可以把p1文件中python对象加载到内存中,再把这个对象赋给p2

print(p2, p2.name, p2.age)                  # <__main__.People object at 0x0000028FBC7C9860> Jack 30

p2.sayhi()                                  # Hi, my name is Jack, and I'm 30

 

你可能感兴趣的:(python)