Refactor to a Dataclass
Advanced · Refactor · from Python Dataclasses: Less Boilerplate, More Readable Code
From the lesson: Python Dataclasses: Less Boilerplate, More Readable Code
Imagine filling out a form where you have to write your name, address, and phone number. Now imagine filling out 50 forms where every single one asks for the same information in a slightly different format. That's what writing Python classes feels like sometimes.
Read the lessonRefactor this regular class into a dataclass. The output must remain the same:
Movie(title='Inception', director='Nolan', year=2010)
TrueReplace the manual __init__, __repr__, and __eq__ with a @dataclass decorator.
class Movie:
def __init__(self, title, director, year):
self.title = title
self.director = director
self.year = year
def __repr__(self):
return f"Movie(title='{self.title}', director='{self.director}', year={self.year})"
def __eq__(self, other):
if not isinstance(other, Movie):
return NotImplemented
return (self.title == other.title and
self.director == other.director and
self.year == other.year)
m1 = Movie('Inception', 'Nolan', 2010)
m2 = Movie('Inception', 'Nolan', 2010)
print(m1)
print(m1 == m2)
More Dataclass exercises
- Create a Product DataclassBeginner
- Playlist with Default TagsIntermediate
- Fix the Dataclass BugIntermediate
- Rectangle with Computed AreaIntermediate
- Predict Frozen BehaviorIntermediate
- Sort Students by GPAIntermediate
All Python exercises · 50 practice problems · Object-Oriented Programming quiz