Object Oriented Python – Object Serialization
Object serialization is an important concept in Python Object-Oriented Programming. It allows you to convert objects into a format that can be stored, transferred, and later reconstructed.
In simple terms, serialization helps you save objects to files or send them over a network.
1. What is Object Serialization?
Object serialization is the process of converting a Python object into a byte stream or structured format (like JSON).
Deserialization is the reverse process—converting data back into a Python object.
Example Concept
Object → Serialization → File/Network → Deserialization → Object
2. Why Use Serialization?
Serialization is useful for:
- Saving program data
- Storing user sessions
- Sending data over APIs
- Saving machine learning models
- Data persistence
3. Types of Serialization in Python
Python provides two main ways:
| Method | Description |
|---|---|
| JSON | Human-readable format |
| Pickle | Python-specific binary format |
4. JSON Serialization (Object to JSON)
JSON is widely used for APIs and web applications.
Example: Convert Object to JSON
import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student = Student("John", 20)
data = json.dumps(student.__dict__)
print(data)
Output
{"name": "John", "age": 20}
5. JSON Deserialization (JSON to Object)
data = '{"name": "John", "age": 20}'
obj = json.loads(data)
print(obj["name"])
6. Custom Object Serialization with JSON
You can control serialization using methods.
import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def to_json(self):
return json.dumps(self.__dict__)
s = Student("Alice", 22)
print(s.to_json())
7. Pickle Serialization (Binary Format)
Pickle is used to serialize Python objects directly.
Example: Serialize Object
import pickle
class Student:
def __init__(self, name):
self.name = name
s = Student("John")
with open("student.pkl", "wb") as file:
pickle.dump(s, file)
Example: Deserialize Object
import pickle
with open("student.pkl", "rb") as file:
obj = pickle.load(file)
print(obj.name)
8. Difference Between JSON and Pickle
| Feature | JSON | Pickle |
|---|---|---|
| Readability | Human-readable | Binary format |
| Speed | Slower | Faster |
| Security | Safe | Not safe for untrusted data |
| Compatibility | Cross-language | Python only |
9. Object Serialization with OOP Design
You can wrap serialization inside classes.
Example: Serializable Class
import json
class User:
def __init__(self, username, email):
self.username = username
self.email = email
def save(self, filename):
with open(filename, "w") as file:
json.dump(self.__dict__, file)
def load(self, filename):
with open(filename, "r") as file:
data = json.load(file)
self.username = data["username"]
self.email = data["email"]
10. Real-World Applications
Object serialization is used in:
- Web APIs (JSON data exchange)
- Machine learning model storage
- Game save systems
- User session management
- Cloud data storage
- Microservices communication
11. Advantages of Serialization
- Saves program state
- Enables data transfer
- Improves persistence
- Supports distributed systems
- Simplifies data storage
12. Common Mistakes
❌ Using Pickle for untrusted data
✔ Avoid due to security risks
❌ Not handling file errors
✔ Always use try-except blocks
❌ Serializing unsupported objects
✔ Convert objects to dictionaries first
13. Best Practices
✔ Prefer JSON for APIs and web apps
✔ Use Pickle only for trusted environments
✔ Validate data before loading
✔ Use helper methods for serialization
✔ Keep data structures simple
Conclusion
Object serialization in Python allows you to convert objects into storable and transferable formats. By using JSON and Pickle, you can easily save, load, and share object data in real-world applications.
Mastering serialization is essential for building APIs, data-driven systems, and scalable Python applications.


0 Comments