Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Object Serialization (Straightline hóa đối tượng)

Serialization là quá trình biến đổi đối tượng thành định dạng có thể lưu trữ (trong file hoặc memory buffer), để sau này có thể deserialize và khôi phục đối tượng gốc từ định dạng serialized. Sử dụng module pickle của Python để thực hiện.

Pickling là gì?

Module pickle dùng để serialize và deserialize cấu trúc đối tượng Python. Quá trình chuyển đổi bất kỳ đối tượng Python nào (list, dict, v.v.) thành byte stream (0 và 1) gọi là pickling hoặc serialization hoặc flattening hoặc marshaling. Byte stream từ pickling có thể chuyển ngược lại thành đối tượng Python bằng quá trình unpickling.

Để pickle một đối tượng:

  • Import pickle
  • Gọi hàm 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('My Vehicle Maruti is {0} and has {1} doors'.format(Maruti.color, Maruti.number_of_doors))
pickle_Maruti = pickle.dumps(Maruti)
print('Here is my pickled Vehicle: ')
print(pickle_Maruti)

Kết quả

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.'

Trong ví dụ: tạo instance của class Car, pickle nó, biến instance thành mảng byte đơn giản. Sau khi pickled, có thể lưu vào file nhị phân hoặc trường DB và khôi phục sau.

Lưu ý: Muốn tạo file chứa đối tượng pickled, dùng phương thức dump() thay vì dumps().

Unpickling

Là ngược lại của pickling: lấy binary stream chuyển thành階層 đối tượng.

Unpickling dùng hàm load() của module pickle, trả về hoàn chỉnh object hierarchy từ byte stream.

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('My Vehicle Maruti is {0} and has {1} doors'.format(Maruti.color, Maruti.number_of_doors))
pickle_Maruti = pickle.dumps(Maruti)

# Unpickle car Maruti tạo instance khác, chiếc xe khác...
unpickle_Maruti = pickle.loads(pickle_Maruti)
Hyundai = unpickle_Maruti
# Đặt màu khác cho instance mới
Hyundai.color = 'Black'
print("Hyundai is {0}".format(Hyundai.color))
print("Maruti is {0}".format(Maruti.color))

Trong ví dụ: pickled xe đầu tiên (Maruti), unpickled vào biến khác (Hyundai) - tức là clone Maruti để tạo Hyundai.

Kết quả

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

Pickle vs JSON

JSON (Javascript Object Notation) là định dạng nhẹ cho trao đổi dữ liệu, đọc được bởi con người. Ưu điểm lớn của JSON so với pickle: tiêu chuẩn, độc lập ngôn ngữ, an toàn và nhanh hơn.

Thay thế khác cho pickle là cPickle, giống pickle nhưng viết bằng C, nhanh hơn 1000 lần. Có thể dùng cùng file cho pickle và 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))

Kết quả

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']

Code: lấy đối tượng (my list), dùng dumps trả về string, rồi loads chuyển string thành JSON object data structure.