6 min read
ā¢Question 35 of 41hardDataclasses and attrs
Modern class definitions.
Dataclasses
Basic Dataclass
code.pyPython
from dataclasses import dataclass, field
@dataclass
class Person:
name: str
age: int
email: str = ""
# Automatic __init__, __repr__, __eq__
p = Person("Alice", 30)
print(p) # Person(name='Alice', age=30, email='')Advanced Features
code.pyPython
from dataclasses import dataclass, field
from typing import List
@dataclass
class Product:
name: str
price: float
tags: List[str] = field(default_factory=list)
_id: int = field(init=False, repr=False)
def __post_init__(self):
self._id = hash(self.name)
# Frozen (immutable)
@dataclass(frozen=True)
class Point:
x: float
y: float
# Ordered comparison
@dataclass(order=True)
class Student:
sort_index: float = field(init=False, repr=False)
name: str
grade: float
def __post_init__(self):
self.sort_index = self.gradeInheritance
code.pyPython
@dataclass
class Animal:
name: str
age: int
@dataclass
class Dog(Animal):
breed: str
dog = Dog("Buddy", 5, "Labrador")Converting to Dict/Tuple
code.pyPython
from dataclasses import asdict, astuple
@dataclass
class Person:
name: str
age: int
p = Person("Alice", 30)
print(asdict(p)) # {'name': 'Alice', 'age': 30}
print(astuple(p)) # ('Alice', 30)Slots for Memory
code.pyPython
@dataclass(slots=True) # Python 3.10+
class Point:
x: float
y: float
# Uses __slots__ for memory efficiency