📊

How to Use Data Classes in Python

PythonIntermediate

Create classes with less boilerplate.

Code Example

Python
from dataclasses import dataclass, field

# Basic dataclass
@dataclass
class Point:
    x: float
    y: float

p1 = Point(1.0, 2.0)
p2 = Point(1.0, 2.0)

print(f"Point: {p1}")
print(f"Equal: {p1 == p2}")

# With default values
@dataclass
class Person:
    name: str
    age: int
    city: str = "Unknown"

person = Person("Alice", 30)
print(f"\nPerson: {person}")

# With methods
@dataclass
class Rectangle:
    width: float
    height: float
    
    def area(self):
        return self.width * self.height
    
    def perimeter(self):
        return 2 * (self.width + self.height)

rect = Rectangle(5, 3)
print(f"\nArea: {rect.area()}")
print(f"Perimeter: {rect.perimeter()}")

# With field options
@dataclass
class Inventory:
    items: list = field(default_factory=list)
    
    def add_item(self, item):
        self.items.append(item)

inv = Inventory()
inv.add_item("apple")
inv.add_item("banana")
print(f"\nInventory: {inv.items}")

# Frozen (immutable)
@dataclass(frozen=True)
class Config:
    host: str
    port: int

config = Config("localhost", 8080)
print(f"\nConfig: {config}")

# Try to modify (will raise error)
try:
    config.port = 9000
except Exception as e:
    print(f"Cannot modify: {e}")

Explanation

Dataclasses auto-generate __init__, __repr__, __eq__. Use @dataclass decorator. Add methods normally. Use field() for defaults. frozen=True for immutable.

Related Tutorials