from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
# Auto-generates: __init__, __repr__, __eq__
p1 = Point(3.0, 4.0)
p2 = Point(3.0, 4.0)
print(p1) # Point(x=3.0, y=4.0)
print(p1 == p2) # True (auto __eq__!)
print(p1.x) # 3.0from dataclasses import dataclass, field
@dataclass
class User:
name: str
age: int = 0 # Default value
active: bool = True # Default value
# tags: list = [] # ❌ MUTABLE DEFAULT BUG!
tags: list = field(default_factory=list) # ✅ Safe!
u1 = User('Alice')
print(u1) # User(name='Alice', age=0, active=True, tags=[])
u2 = User('Bob', age=30, tags=['admin'])
print(u2) # User(name='Bob', age=30, active=True, tags=['admin'])from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
tags: list = field(default_factory=list)
internal_id: int = field(default=-1, repr=False) # Hidden from repr
description: str = field(default='', compare=False) # Excluded from __eq__
p = Product('Laptop', 999, tags=['tech'], internal_id=42, description='A laptop')
print(p)
# Product(name='Laptop', price=999, tags=['tech'], description='A laptop')
# internal_id NOT in repr!@dataclass(frozen=True)
class ImmutablePoint:
x: float
y: float
p = ImmutablePoint(1, 2)
# p.x = 10 # FrozenInstanceError!
print(p) # ImmutablePoint(x=1.0, y=2.0)
# Frozen dataclasses are hashable — can be dict keys / set members
points = {ImmutablePoint(0,0), ImmutablePoint(1,1), ImmutablePoint(0,0)}
print(len(points)) # 2 (deduplicated!)@dataclass
class Circle:
radius: float
area: float = field(init=False) # NOT set in __init__
def __post_init__(self):
self.area = 3.14159 * self.radius ** 2
c = Circle(5)
print(c) # Circle(radius=5, area=78.53975)@dataclass
class Animal:
name: str
age: int
@dataclass
class Dog(Animal):
breed: str
# Fields are ordered: name, age (from Animal), then breed (from Dog)
d = Dog('Rex', 5, 'Labrador')
print(d) # Dog(name='Rex', age=5, breed='Labrador')Create a `Student` dataclass with `name: str`, `gpa: float`, `courses: list` (use default_factory). Add a `@property gpa_letter` that returns 'A' if gpa >= 3.7, 'B' if >= 3.0, 'C' if >= 2.0, else 'F'. Create a `GradStudent(Student)` dataclass adding `thesis: str`. Create a frozen `Config` dataclass with `debug: bool = False`, `max_retries: int = 3`. Demonstrate all features including hashability of Config.