Python Data Classes Tutorial
Simplify your Python code with data classes and modern Python features.
# Python Data Classes Tutorial
Python data classes, introduced in Python 3.7, provide a decorator for automatically generating special methods for classes that primarily store data.
## Basic Data Class
```python
from dataclasses import dataclass
@dataclass
class User:
name: str
email: str
age: int
active: bool = True
user = User("Alice", "alice@example.com", 30)
print(user) # User(name='Alice', email='alice@example.com', age=30, active=True)
```
## Auto-Generated Methods
Data classes automatically generate:
- `__init__()`
- `__repr__()`
- `__eq__()`
## Immutable Data Classes
```python
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(1.0, 2.0)
# p.x = 3.0 # Raises FrozenInstanceError
```
## Default Values and Factories
```python
from dataclasses import dataclass, field
from typing import List
@dataclass
class ShoppingCart:
items: List[str] = field(default_factory=list)
total: float = 0.0
def add_item(self, item: str, price: float):
self.items.append(item)
self.total += price
```
## Comparison and Ordering
```python
@dataclass(order=True)
class Product:
name: str = field(compare=False)
price: float
p1 = Product("Widget", 10.0)
p2 = Product("Gadget", 15.0)
print(p1 < p2) # True
```
## Post-Init Processing
```python
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
self.area = self.width * self.height
```
## When to Use Data Classes
- Classes that primarily store data
- Want automatic method generation
- Need immutability (frozen=True)
- Value objects in domain models
Data classes reduce boilerplate and make your code more maintainable. Use them whenever appropriate!
You Might Also Like
TypeScript Generics Tutorial
Write type-safe, reusable code with TypeScript generics and advanced type patterns.
Read more →
Unit Testing with Jest
Write robust unit tests for your JavaScript applications using Jest framework.
Read more →
Python Django vs Flask Comparison
Choose the right Python web framework for your project with this detailed comparison.
Read more →