2-Minute Python Guide: dataclasses
Python's @dataclass decorator is a game-changer for creating simple classes. Let's compare a regular class with a @dataclass to see the benefits.
Regular Class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
def __eq__(self, other):
return self.name == other.name and self.age == other.age
@dataclass
from dataclasses import dataclass, field
@dataclass
class Person:
name: str
age: int
occupation: str = field(default="Unknown")
frozen: bool = field(default=False, repr=False)
# Add frozen=True as a decorator argument to make the class immutable
@dataclass(frozen=True)
class ImmutablePerson:
name: str
age: int
Notice how @dataclass automatically generates __init__, __repr__, and __eq__ methods, saving you time and boilerplate code. The field function allows for custom attribute initialization, and frozen=True makes the class immutable.
Takeaway: Python's @dataclass is a powerful tool for creating simple, efficient classes. By using @dataclass and its associated functions like field, you can write less code and focus on the logic of your program. Give it a try and simplify your class definitions today!
Follow me on Dev.to for daily Python tips and quick guides!
Top comments (0)