In Python, dataclasses are used to create classes that are primarily used to store data. These classes are similar to normal classes, but they provide several powerful features for free such as automatic creation of __init__
, __repr__
, and other methods, default values for attributes, typing, and more.
To create a dataclass in Python, you must first import the dataclass
decorator from the dataclasses
module. Here's an example of how to create a simple data class:
main.py109 chars8 lines
In this example, we created a Person
dataclass with three attributes: name
, age
, and email
. We used the dataclass
decorator and specified the types of each attribute. We also set a default value for email
.
We can now create instances of the Person
class and access their attributes:
main.py131 chars5 lines
As you can see, creating a dataclass is very simple and can save you a lot of time and boilerplate code.
gistlibby LogSnag