Dataclasses
Some classes mostly just store data. For these, a dataclass can write the common methods for you. The first line of the example imports the dataclass tool from Python's built-in dataclasses module. You will learn more about importing in the Modules section.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
first = Point(3, 4)
same_point = Point(3, 4)
print(first)
print(first == same_point)
Output:
Point(x=3, y=4)
True
@dataclass is a decorator. A decorator is a line that starts with @ and sits just above a class. It adds features to the class. Here it writes __init__ for you. It also gives the class a readable printout, and it makes == compare the field values.
Each line such as x: int declares a field. The : int part is a type annotation. It is a note that says what type the field should hold. Python only treats it as a note. It does not check the type when the program runs.
A dataclass can also have methods and default values for its fields. Write a normal class by hand when creating an object needs a lot of checking or setup work.
In the exercise, add the decorator and the fields.