Câu hỏi phỏng vấn Python
Câu hỏi

What is Pickling and Unpickling?

Câu trả lời

Pickling and unpickling are terms used in Python to describe the process of serializing and deserializing objects, respectively. These processes are crucial for saving Python objects to a file or transmitting them over a network by converting them into a byte stream and then reconstructing them back into Python objects.

Pickling

Pickling, also known as serialization, involves converting a Python object hierarchy into a byte stream. This is typically done to save the state of an object so that it can be persisted to disk or sent over a network. The pickle module in Python provides this functionality through the dump() and dumps() functions. The dump() function serializes an object directly to a file-like object, while dumps() returns the serialized object as a byte string[1][2][3].

Here is a simple example of pickling:

python Copy
import pickle

# Define a Python object
person = {"name": "Alice", "age": 30, "gender": "female"}

# Pickle the object to a binary file
with open("person.pickle", "wb") as file:
    pickle.dump(person, file)

Unpickling

Unpickling is the inverse process of pickling. It involves converting a byte stream back into a Python object hierarchy. This is useful for reconstructing Python objects from files or network streams where the byte stream was previously generated by pickling. The pickle module provides the load() and loads() functions for this purpose. The load() function deserializes from a file-like object, while loads() deserializes from a byte string[1][2][...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

What is the difference between @staticmethod and @classmethod ?

middle

What's the difference between lists and tuples ?

senior

Why Python (CPython and others) uses the GIL?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào