Python 对象序列化

pythonserver side programmingprogramming更新于 2025/5/12 22:36:17

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

什么是 pickling?

Python pickle 模块用于序列化和反序列化 Python 对象结构。将任何类型的 Python 对象(列表、字典等)转换为字节流(0 和 1)的过程称为 pickling 或序列化或扁平化或编组。我们可以通过一个称为 unpickling 的过程将字节流(通过 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),我们获取二进制流并将其转换为对象层次结构。

反 pickle 是使用 pickle 模块的 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),然后我们将其 unpickled 到另一个变量 (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 对象数据结构。


相关文章


有用资源