Python Classes VS DataClasses: Which one to choose from?
If you’re reading this article, it means either you are looking answer to the same question or you already know it but want to be sure of it.
Whatever be the case, I’m sure this article will help you clear all your doubts. So let’s begin
Classes in Python
A class in Python is no different than a class in any other object-oriented language. A class is a logical entity/user-created data structure which provides a way to encapsulate data and functions together.
Object creation allows to access the data and member functions of a class.
DataClasses in Python
A data class is a regular class with a @dataclass decorator. It is a new feature that has been introduced in Python 3.7 and has been backported to version 3.6.
Anyone having python 3.6 and above can utilize this module.
Data classes make our life easier by adding special methods such as __init__(), __repr__(), etc into our class automatically.
Let’s discuss some points to highlight the difference between Classes and Data classes in detail :
1. A regular class is created using the keyword ‘class’ before the class name. In regular class, one has to add dunder functions such as __init__() and __repr__().
A data class is created by importing dataclass from dataclasses and adding a decorator ‘@dataclass’ above the regular class.
Adding this decorator makes implementing classes much simpler by taking care of dunder methods and it works the same as a regular class with no performance penalty.
2. Class attributes in data class have type annotations which let us know the type of data handled by these class attributes. Type hinting in data classes increases code readability. Using data classes over regular classes will help in building and maintaining cleaner code and helps to understand types flows in the code.
3. Equality Comparisons in class can be much of work because we need to define comparison functions such as __lt__(), __le__(),__ge__(), etc. whereas in Dataclasses @dataclass decorator takes care of comparison functions on our behalf.
4. Dataclass provides a way to initialize variables outside the __init__() using a built-in function __post_init__()
From the above points, we can conclude that DataClasses is a clear winner.