This article is about the basics of dataclass in modern Python.
Dataclasses are a relatively new feature added to Python 3.7 that simplifies the process of creating classes to model and store data. They are essentially a shortcut to defining classes that have a specific set of attributes or properties. They automatically add the __init__(), __repr__(), and other common methods, therefore significantly reducing the amount of boilerplate code that is needed when defining classes.
This is a minimum example of defining a dataclass:
from dataclasses import dataclass @dataclass class Product: name: str price: float
When we decorate the class with @dataclass, Python automatically generates an __init__() method that takes 2 arguments: name and price. It also generates a __repr__() method that returns a string representation of the object:
from dataclasses import dataclass @dataclass class Product: name: str price: float product = Product('Apple', 1.99) print(product.__repr__())
I believe that examples will help you learn and grasp the knowledge better than boring words. Below are some real-world examples of implementing dataclasses in Python.
A simple class to present a book
from dataclasses import dataclass @dataclass class Book: title: str author: str pages: int price: float book = Book("Sling Academy Ruins", "Blazing Bull", 1208, 9.99) print(book)
Book(title='Sling Academy Ruins', author='Blazing Bull', pages=1208, price=9.99)
A class to present a rectangle
from dataclasses import dataclass @dataclass class Rectangle: width: float height: float # this method calculates the area of the rectangle def area(self): return self.width * self.height # this method calculates the perimeter of the rectangle def perimeter(self): return 2 * (self.width + self.height) # Try it rectangle = Rectangle(3, 4) print(rectangle.area()) print(rectangle.perimeter())
The above is the first step to help you familiarize yourself with dataclasses. In the next articles, we will explore more advanced things.