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 物件資料結構。