共計 851 個字符,預計需要花費 3 分鐘才能閱讀完成。
Python 對象序列化可以通過 pickle 模塊來實現。pickle 模塊提供了一種簡單的持久化 Python 對象的方法,它將 Python 對象轉化為一系列字節流,可以存儲在文件或者通過網絡傳輸,然后再將字節流重新轉化為原來的 Python 對象。
以下是一個簡單的示例代碼,演示了如何使用 pickle 模塊進行對象的序列化和反序列化:
import pickle
# 定義一個對象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 序列化對象
def serialize(obj, file_path):
with open(file_path, 'wb') as file:
pickle.dump(obj, file)
# 反序列化對象
def deserialize(file_path):
with open(file_path, 'rb') as file:
obj = pickle.load(file)
return obj
# 使用示例
p = Person('Alice', 25)
serialize(p, 'person.pkl')
p_deserialized = deserialize('person.pkl')
print(p_deserialized.name) # 輸出:Alice
print(p_deserialized.age) # 輸出:25
在上述代碼中,我們定義了一個 Person
類,然后使用 pickle
模塊中的 dump
方法將 Person
對象序列化到文件 person.pkl
中。接著,我們使用 pickle
模塊中的 load
方法從文件中反序列化出一個對象p_deserialized
,并打印出其中的屬性值。
需要注意的是,在使用 pickle 進行對象的序列化和反序列化時,要確保讀取和寫入文件的模式分別為 rb
和wb
,這樣可以保證以二進制的形式進行讀寫操作。
丸趣 TV 網 – 提供最優質的資源集合!
正文完