3. Data Classes
These examples show how the dataclasses module simplifies creating and managing data objects while providing flexibility for real-world scenarios. Let me know if you'd like additional examples or furt
1. Basic Data Class
Copy
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
person = Person(name="Alice", age=30)
print(person) # Output: Person(name='Alice', age=30)2. Default Values in Data Classes
Copy
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
price: float = 9.99
book = Book(title="Python 101", author="John Doe")
print(book) # Output: Book(title='Python 101', author='John Doe', price=9.99)3. Immutable Data Classes
Copy
4. Post-Initialization Processing
Copy
5. Comparing Data Class Instances
Copy
6. Default Factory for Mutable Fields
Copy
7. Excluding Fields from repr
Copy
8. Data Classes with Type Hints
Copy
9. Inheriting from Data Classes
Copy
10. Using asdict and astuple
Copy
Last updated