If you don't like to write boilerplate code while creating a class in Python, then you will love data classes in Python.
Data class is a convenient way of creating a class in Python. It is just like a regular class in Python but when you create a data class, you don't have to write the basic and most obvious functions __init__()
, __repr__()
, and __eq__()
. These functions are by default implemented for you when you create a data class.
Let's take an example of creating a student class using data classes.
from dataclasses import dataclass
@dataclass
class Student:
name: str
program: str
age: int
First, you have to import dataclass
decorator from the dataclasses
module. dataclass
is a part of the standard library in Python 3.7 and above, so you don't need to install any package to use data classes.
Now, let's create a student object and print it.
You can see the output of printing the Student
data class object. If you print a regular class object, it will print the position of the object in memory. This is because our Student
class implicitly has __repr__()
method which needs to be explicitly implemented in case of a regular class.
Now, let's see how easy it is to compare data class objects.
We have created another object of Student
called joe_copy
which is the replica of joe
. We can directly compare the 2 instances of Student
because our Student
has implicitly defined __eq__()
method. If we compare 2 instances of a regular class in Python directly like the above, we would get False.
If we create the same Student
class using regular class syntax, then it would look like this.
class Student:
def __init__(self, name, program, age):
self.name = name
self.program = program
self.age = age
def __repr__(self):
return (f'{self.__class__.__name__}'
f'(name={self.name}, program={self.program}, age={self.age})')
def __eq__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return (self.name, self.program, self.age) == (other.name, other.program, other.age)
This was just a basic introduction to Python data classes. Of course, you can do other OOP stuff like inheritance using data classes with more convenience and better readability. I have attached some resources below if you want to dive deeper into Python data classes. Remember that
Readability Counts
Additional Resources: