Python Data Class
One of Python 3.7’s new features is data classes. And you may have to install them as a library for Python versions lower than 3.7. (pip install data classes).
With data classes, you can properly initialize, represent, and compare your objects without having to create boilerplate code. The brand-new @data class decorator is used to build it. In this article, you will learn how to construct and utilize the Python data class, which is available in Python 3.7 and later.
Understanding Python Data Classes
Python data classes hold data. This module was created because we occasionally create classes that serve merely as data containers, which requires us to write boilerplate code with numerous arguments, an unsightly __init__ method, and overridden functions.
Data classes ensure you don’t go through the hassle of writing such boilerplates while also incorporating more practical methods. Furthermore, because data classes are a relatively recent addition to the Python ecosystem, they impose contemporary standards like type annotations. The Python data class decorator is a code generator that, in the background, automatically adds additional methods.
Basic Functions of the Python Data Class
DataClasses in Python are similar to regular classes, but they already have several fundamental operations including instantiation, comparison, and printing of the classes.
The syntax of the data class is:
Syntax: @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
A data class provides the following methods:
- __repr__
- __init__
- __eq__
Additionally, Dataclasses offer a wealth of features that make coding enjoyable and simple. Data classes operate as data containers and represent easily readable objects.
By using a data class, you may avoid the trouble of writing boilerplate code and defining internal fields without having to. Once more, you can easily define custom sorting and access attributes.
How the Python Data Class Differs From the Regular Python Class
The Python data class optimizes the codes we write with the normal Python class. Let’s use this example to represent our claims.
class Personal_data:
def __init__(self, firstname, lastname, sex):
self.firstname = firstname
self.lastname = lastname
self.sex = sex
def __repr__(self):
return f"Person(firstname='{self.firstname}', lastname='{self.lastname}', sex={self.sex})"
def __eq__(self, other):
return self.firstname == other.firstname and \
self.lastname == other.lastname and \
self.sex == other.sex
def greeting(self):
print(f'Hello, {self.firstname} {self.lastname} {self.sex}')
p = Personal_data('Jona Chris', 'Emmanuels', 'male')
print(p)
#Output
Person(firstname=’Jona Chris’, lastname=’Emmanuels’, sex=’male’)
Note: We must implement the __repr__() method because we need to be able to quickly print the object for debugging.
Because we want to compare the objects to see if they are the same “person,” we also implement the __eq__() method.
Let’s now examine how the data class can make this better. With Python 3.7 and later, the data class is already included; we just need to import it.
from dataclasses import dataclass
@dataclass
class Person:
firstname: str
lastname: str
Sex: str
def greeting(self):
print('hello, {self.firstname}, {self.lastname}, {self.Sex}')
p = Person('Philip', 'Emmanuels', 'male')
print(p)
#Output
Person(firstname=’Philip, lastname=’Emmanuels’, sex=male)
You can anticipate that the data class we just generated using the decorator will have every characteristic we previously described in the normal class. Yes, all of the other methods are generated automatically in the background, with the exception of the greeting() function, which is a true bespoke class method.
Example 2:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person('Gabo', 64)
To make the Person class a data class, you follow these steps:
- First, import the data class decorator from the data classes module:
- Second, decorate the Person class with the data class decorator and declare the attributes:
from data classes import data class
@dataclass
class Person:
name: str
age: int
p = Person('John Doe', 34)
print(p)
Data classes make it simple to interact with classes that serve as data containers. It uses personalized ordering and comparisons and legibly represents objects.