Python 对象序列化


序列化是一个将对象转换为可存储/保存(在文件或内存缓冲区中)的格式的过程,因此我们能够稍后反序列化它并从序列化格式中恢复原始内容/对象。我们将使用 python pickle 模块来执行所有这些操作。

什么是 pickle?

Python pickle 模块用于序列化和反序列化 Python 对象结构。将任何类型的 Python 对象(列表、字典等)转换为字节流(0 和 1)的过程称为 pickle 或序列化或扁平化或封送。我们可以通过称为反 pickle 的过程将字节流(通过 pickle 生成)转换回 Python 对象。

要 pickle 一个对象,我们只需要 -

  • 导入 pickle
  • 调用 dumps() 函数
import pickle
class Vehicle:
   def __init__(self, number_of_doors, color):
      self.number_of_doors = number_of_doors
      self.color = color
class Car(Vehicle):
   def __init__(self, color):
      Vehicle.__init__(self, 5, color)
Maruti = Car('Red')
print(str.format('My Vehicle Maruti is {0} and has {1} doors', Maruti.color, Maruti.number_of_doors))
pickle_Maruti = pickle.dumps(Maruti)
print('Here is my pickled Vehicle: ')
print(pickle_Maruti)

输出

My Vehicle Maruti is Red and has 5 doors
Here is my pickled Vehicle:
b'\x80\x03c__main__\nCar\nq\x00)\x81q\x01}q\x02(X\x0f\x00\x00\x00number_of_doorsq\x03K\x05X\x05\x00\x00\x00colorq\x04X\x03\x00\x00\x00Redq\x05ub.'

在上面的示例中,我们创建了一个 Car 类的实例,然后将其 pickle,将我们的汽车实例转换为简单的字节数组。在我们的汽车实例被 pickle 后,我们可以轻松地将其存储在二进制文件或数据库字段中,并稍后将其恢复以将这组字节转换回对象层次结构。

注意:如果我们想创建一个包含 pickle 对象的文件,我们需要使用 dump() 方法而不是 dumps() 方法。

反序列化

它是 pickle 的逆操作,我们获取二进制流并将其转换为对象层次结构。

反序列化是使用 pickle 模块的 load() 函数完成的,并从字节流中返回完整的对象层次结构。

以下是 load

import pickle
class Vehicle:
   def __init__(self, number_of_doors, color):
      self.number_of_doors = number_of_doors
      self.color = color
class Car(Vehicle):
   def __init__(self, color):
      Vehicle.__init__(self, 5, color)
Maruti = Car('Red')
print(str.format('My Vehicle Maruti is {0} and has {1} doors', Maruti.color, Maruti.number_of_doors))
pickle_Maruti = pickle.dumps(Maruti)
#Now, let's unpickle our car Maruti creating another instance, another car ... unpickle_Maruti
Hyundai = pickle.loads(pickle_Maruti)
#Set another color of our new instance
Hyundai.color = 'Black'
print(str.format("Hyundai is {0} ", Hyundai.color))
print(str.format("Maruti is {0} ", Maruti.color))

在上面的示例中,您可以看到我们已经 pickle 了我们的第一辆汽车对象(Maruti),然后我们将其反序列化到另一个变量(Hyundai),因此从某种意义上说,我们克隆了 Maruti 来创建 Hyundai。

输出

My Vehicle Maruti is Red and has 5 doors
Hyundai is Black
Maruti is Red

Pickle 与 JSON

JSON 代表 Javascript 对象表示法,是一种用于数据交换的轻量级格式,并且是人类可读的。JSON 相对于 pickle 的一大优势在于它是标准化的并且独立于语言。它比 pickle 更安全、更快。

pickle 的另一种替代方案是 cPickle,它非常类似于 pickle,但它是用 C 语言编写的,速度提高了 1000 倍。您可以对 pickle 和 cPickle 使用相同的文件。

import json
mylist = [2, 4, 5, "ab", "cd", "ef"]
print("Here is my list: ", mylist)
json_string = json.dumps(mylist )
print("Here is my json encoded object: ", json_string)
print ("Here is JSON back to a data structure: ",json.loads(json_string))

输出

Here is my list: [2, 4, 5, 'ab', 'cd', 'ef']
Here is my json encoded object: [2, 4, 5, "ab", "cd", "ef"]
Here is JSON back to a data structure: [2, 4, 5, 'ab', 'cd', 'ef']

在上面的代码中,我们首先获取对象(我的列表)并使用“dumps”方法返回一个字符串,然后要将 JSON 加载回数据结构,我们使用“loads”方法将字符串转换为 JSON 对象数据结构。

更新于: 2020年6月30日

624 次查看

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.