Python dataclass: Taking advantage of the new decorator
As you may already understand from this simple example, an important aspect of dataclasses is that you get many functionalities “for free”, which means you do not have to implement them by hand. Functions like
__init__ (class initializer),
__repr__(function returning a string representation of the class) and
__eq__ (function to compare various instances with each other) are already implemented.
The notation and the syntax is simple: After you declare a class under the “@dataclass” decorator, then you simple declare the fields of your class along with there respective data type.
Dataclasses also provide the functionality to declare default values for fields if you want to. Below you can see an example of a dataclass with default values for the fields name and surname. Note that in case you do not want to set default values for all fields, the fields that have default values must be declared at the end of the fields list.