Introduction to Data Classes in Python














































Introduction to Data Classes in Python



INTRODUCTION TO DATA CLASSES IN PYTHON

Data classes have been a recent addition to the python standard libraries since Python 3.7 which is a utility tool to make structured classes especially for storing the data. These Classes have certain properties and functions which deal specifically with the data and its representation.
One of the new features of Python 3.7, a new one is the decorator @dataclass that simplifies the creation of data classes By default, data classes come with __init__, __repr__ and __eq__methods implemented so we don't have to implement these methods by ourself. 
Data classes write boiler-plate code for you and simplify the process of creating classes because it comes with some methods implemented which make the task easy.

Let us take an example:

A Class used to store the values of point is simply a class with 3 fields(a,b,c).

# A basic Data Class
# Importing dataclass module
from dataclasses import dataclass
@dataclass
class Point:
"""A class for holding a point content"""
# Attributes Declaration
# using Type Hints
a: int
b: float
c: float
# A DataClass object
p = Point(
5, 2.5,7.8)

OUTPUT:


We often need to add a constructor, a representation method, a comparison function. These functions are very difficult and this is exactly what should be handled transparently by the language.
By default, this will auto-generate the functions needed to instantiate, compare and print the data class instances. In other words, this is equivalent to:
class Point:
"""A class for holding a point content"""
# Equivalent Constructor
def __init__(self, a: int, b: float, c: float):
self.a = a
self.b = b
self.c = c
# Equivalent Representation
def __repr__(self):
return f"Point(a={self.a}, b={self.b}, c={self.c})"
# Equivalent Comparison function
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.a, self.b, self.c) == (other.a, other.b, other.c)
return NotImplemented
# A DataClass object
p = Point(
5, 2.5,7.8)
print(p)


OUTPUT:






Comments