Curriculum
In Python 3.7 and later versions, the dataclass
decorator provides a way to automatically generate special methods like __init__
, __repr__
, __eq__
, __ne__
, and others for a class with a minimum amount of boilerplate code. It is used to define simple classes that mainly just hold data, and allows us to avoid writing lots of repetitive boilerplate code.
Here’s an example of how to use the dataclass
decorator:
from dataclasses import dataclass @dataclass class Person: name: str age: int email: str = '' person = Person("Alice", 25, "[email protected]") print(person)
In this example, we define a Person
class using the dataclass
decorator. We specify the fields of the class as parameters to the decorator. In this case, we have three fields: name
, age
, and email
.
When we use the dataclass
decorator, it automatically generates the __init__
, __repr__
, and other special methods for us. We can then create instances of the Person
class by passing the values for the fields as arguments to the constructor.
In the example, we create an instance of the Person
class and print it to the console. The __repr__
method generated by the dataclass
decorator is used to produce a string representation of the Person
object.
The output of the above code will be:
Person(name='Alice', age=25, email='[email protected]')
As you can see, we were able to create a simple data class with a minimum amount of boilerplate code using the dataclass
decorator. It’s a useful feature that makes it easy to define simple classes that mainly just hold data.