Data Classes in Python

In this tutorial we are going to learn about data classes in Python.

data classes have been a recent edition in Python standard library since Python 3.7.0. These are just normal classes that help us towards packing state, more than containing a lot of logic. Every time we create a class that mostly contains different types of attributes are the data classes module makes it easy for us to create data classes.  It helps us to create classes that contain only fields such as data and methods to access the fields.

They serve as ampules for data that can be used by other classes that implement the operation of the application.we can also use data class in Python3.6 by install data classes library. Data classes have some magic functions predefined in it which help us provide a structured decorated output for the class.we can also use data class as a container and also data classes simplify the process of the classes and provides a structured output.

Representation of Data Classes

from dataclasses import dataclass
  • To create a data class we need to import data classes from the library .
  • Data class is an inbuilt module in Python, it is a decorator class function.

 

@dataclass
class stu:
    name: str
    age: int
    marks: int
  • A @dataclass is a decorator function that helps us form a standard and structured output.
  • We are providing the data types to the name age and marks.
info=stu('Anmol',20,88)
info.name,info.age,info.marks

Output

('Anmol', 20, 88)

info
stu(name='Anmol', age=20, marks=88)

We can see that we get a structured output of the class.

Now if we take another object info2 with the same parameters we get our output as true

info2=stu('Anmol',20,88)
info==info2
True

We get true because the data classes contain:

  • __init__(), constructor, to classes
  • __repr__(), constructor, to class to give us a structured output.

Data classes create a class which provides the class some extra behavior in the form of some magic functions or by defining some magic function in the class.

Leave a Reply

Your email address will not be published. Required fields are marked *