Junior — Middle
Explain the concept and use of dataclasses in Python.
sobes.tech AI
Answer from AI
Dataclasses in Python are a convenient way to create classes primarily intended for storing data, without the need to write a lot of boilerplate code.
Main features of dataclasses:
- Automatically generate methods like
__init__,__repr__,__eq__, and others. - Easily define fields with types.
- Support default values and value factories.
Example usage:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p1 = Point(10, 20)
print(p1) # Point(x=10, y=20)
This simplifies creating simple classes for data storage, making the code cleaner and easier to maintain.