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
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
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
4. Post-Initialization Processing
5. Comparing Data Class Instances
6. Default Factory for Mutable Fields
7. Excluding Fields from repr
8. Data Classes with Type Hints
9. Inheriting from Data Classes
10. Using asdict and astuple
Last updated