The Wayback Machine - https://web.archive.org/web/20240816172508/https://www.geeksforgeeks.org/data-classes-in-python-an-introduction/
Open In App

Data Classes in Python | An Introduction

Last Updated : 23 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.
DataClasses in widely used Python3.6 
Although the module was introduced in Python3.7, one can also use it in Python3.6 by installing dataclasses library. 
 

pip install dataclasses

The DataClasses are implemented by using decorators with classes. Attributes are declared using Type Hints in Python which is essentially, specifying data type for variables in python.
 

Python3




# A basic Data Class
 
# Importing dataclass module
from dataclasses import dataclass
 
@dataclass
class GfgArticle():
    """A class for holding an article content"""
 
    # Attributes Declaration
    # using Type Hints
 
    title: str
    author: str
    language: str
    upvotes: int
 
# A DataClass object
article = GfgArticle("DataClasses",
                     "vibhu4agarwal",
                     "Python", 0)
print(article)


Output: 
 

GfgArticle(title=’DataClasses’, author=’vibhu4agarwal’, language=’Python’, upvotes=0) 
 

The two noticeable points in above code. 
 

  • Without a __init__() constructor, the class accepted values and assigned it to appropriate variables.
  • The output of printing object is a neat representation of the data present in it, without any explicit function coded to do this. That means it has a modified __repr__() function.

The dataclass provides an in built __init__() constructor to classes which handle the data and object creation for them. 
 

Python3




article = GfgArticle()


TypeError: __init__() missing 4 required positional arguments: ‘title’, ‘author’, ‘language’, and ‘upvotes’ 
 

We can also modify the functioning of in-built constructor by passing certain arguments or using special functions which will be discussed in further articles.
Equality of DataClasses 
Since the classes store data, checking two objects if they have the same data is a very common task that’s needed with dataclasses. This is accomplished by using the == operator. 
Below is the code for an equivalent class for storing an article without a dataclass decorator. 
 

Python3




class NormalArticle():
    """A class for holding an article content"""
 
    # Equivalent Constructor
    def __init__(self, title, author, language, upvotes):
        self.title = title
        self.author = author
        self.language = language
        self.upvotes = upvotes
 
# Two DataClass objects
dClassArticle1 = GfgArticle("DataClasses",
                            "vibhu4agarwal",
                            "Python", 0)
dClassArticle2 = GfgArticle("DataClasses",
                            "vibhu4agarwal",
                            "Python", 0)
 
# Two objects of a normal class
article1 = NormalArticle("DataClasses",
                         "vibhu4agarwal",
                         "Python", 0)
article2 = NormalArticle("DataClasses",
                         "vibhu4agarwal",
                         "Python", 0)


Python3




print("DataClass Equal:", dClassArticle1 == dClassArticle2)
print("Normal Class Equal:", article1 == article2)


Output: 
 

DataClass Equal: True
Normal Class Equal: False

Equality between two objects using == operator in python checks for the same memory location. Since two objects take different memory locations on creation, the output for equality is False. Equality between DataClass objects checks for the equality of data present in it. This accounts for True as output for equality check between two DataClass objects which contain same data.
 



Similar Reads

Data Classes in Python | Set 2 (Decorator Parameters)
Prerequisite: Data Classes in Python | Set 1 In this post, we will discuss how to modify the default constructor which dataclass module virtually makes for us. dataclass() decorator - @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) By changing the values of these parameters, we can modify the b
4 min read
Data Classes in Python | Set 3 (dataclass fields)
Prerequisite: Data Classes in Python Set 1 | Set 2 In this post we will discuss how to modify certain properties of the attributes of DataClass object, without explicitly writing code for it using field function. field() function - dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata
4 min read
Data Classes in Python | Set 4 (Inheritance)
Prerequisites: Inheritance In Python, Data Classes in Python | Set 3 In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited. from dataclasses import dataclass @dataclass class Article: title: str content: str author
2 min read
Data Classes in Python | Set 5 (post-init)
Prerequisite: Data Classes in Python | Set 4 In this post, we will discuss how to modify values of some attributes during object creation without coding it in __init__() by using post-init processing. __post_init__(): This function when made, is called by in-built __init__() after initialization of all the attributes of DataClass. Basically, object
2 min read
Data Classes in Python | Set 6 (interconversion to and from other datatypes)
Prerequisite: Data Classes in Python | Set 5 In the last post of DataClass series, we will discuss how to get values of a DataClass object into a dictionary or tuple pairs and how to create a DataClass in a different way - from values, instead of defining it directly. asdict() function - dataclasses.asdict(instance, *, dict_factory=dict) One can si
2 min read
The Ultimate Guide to Data Classes in Python 3.7
This article discusses data classes in Python 3.7 and provides an introductory guide for data classes in Python 3.7 and above. Data Class is a new concept introduced in Python 3.7 version. You can use data classes not only as a knowledge container but also to write boiler-plate code for you and simplify the process of creating classes since it come
4 min read
How to Dynamically Load Modules or Classes in Python
Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it. Note: For more information, refer to Python Modules Example: A simple example of importing a module is shown below in which, there are
3 min read
Create Classes Dynamically in Python
A class defines a collection of instance variables and methods to specify an object type. A class can be used to make as many object instances of the type of object as needed. An object is an identified entity with certain attributes (data members) and behaviours (member functions). Group of objects having similar characteristics and behaviour are
2 min read
SQLAlchemy - Mapping Python Classes
SQLAlchemy is a popular Python library that provides a nice API for interacting with databases. One of its key features is the ability to map Python classes to database tables, allowing you to use Python objects to represent rows in a database table. This is known as an "object-relational mapper" (ORM). Types of Mappings in Python Classes In SQLAlc
7 min read
Comparing Old-Style and New-Style Classes in Python
In Python, the difference between old-style and new-style classes is based on the inheritance from the built-in object class. This distinction was introduced in Python 2.x and was fully adopted in Python 3.x, where all classes are new-style classes. In this article, we will see the difference between the old-style and new-style classes in Python. P
4 min read
Python Classes and Objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it to maintain its state. Class instances can als
11 min read
Abstract Classes in Python
An abstract class can be considered a blueprint for other classes. It allows you to create a set of methods that must be created within any child classes built from the abstract class. A class that contains one or more abstract methods is called an abstract class. An abstract method is a method that has a declaration but does not have an implementa
8 min read
Why do Python classes inherit object?
In Python, every class you create inherits from a special class known as an object. This foundational element simplifies and empowers Python programming. When a new class is defined without specifying a superclass, Python assumes that it inherits from the object class. This is referred to as a "new-style" class declaration and was introduced in Pyt
3 min read
An Introduction to Polars: Python's Tool for Large-Scale Data Analysis
Polars is a blazingly fast Data Manipulation library for Python, specifically designed for handling large datasets with efficiency. It leverages Rust's memory model and parallel processing capabilities, offering significant performance advantages over pandas in many operations. Polars provides an expressive API for data manipulation tasks like filt
4 min read
Scala | Value Classes
Value classes are a new mechanism which help to avoid allocating run time objects. AnyVal define value classes. Value classes are predefined, they coincide to the primitive kind of Java-like languages. There are nine predefined value types : Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean. equals or hashCode cannot redefine by a valu
2 min read
Don't Let Your Geographical Location Be A Barrier In Your Success - Live Classes By GeeksforGeeks
Winter is coming and so is the placement season! And there are many companies that recruit during this time including product-based companies, startups or service-based companies. So if you want to succeed and bag your dream job, thorough interview preparation is a must!!! Now I am sure interviews scare you a lot, just like most candidates!!! But y
6 min read
How to convert unstructured data to structured data using Python ?
Prerequisite: What is Unstructured Data? Sometimes machine generates data in an unstructured way which is less interpretable. For example, Biometric Data, where an employee does Punch - IN or OUT several times with mistakes. We can not analyze the data and identify the mistakes unless it's in a tabular form. In this article, we will take unstructur
5 min read
Python - Convert Tick-by-Tick data into OHLC (Open-High-Low-Close) Data
In this post, we'll explore a Python pandas package feature. We frequently find queries about converting tick-by-tick data to OHLC (Open, High, Low and Close). Using pandas kit this can be done with minimum effort. The OHLC data is used over a unit of time (1 day, 1 hour etc.) to perform a technical analysis of price movement. The First Step: The f
2 min read
How to convert categorical data to binary data in Python?
Categorical Data is data that corresponds to the Categorical Variable. A Categorical Variable is a variable that takes fixed, a limited set of possible values. For example Gender, Blood group, a person having country residential or not, etc. Characteristics of Categorical Data : This is mostly used in Statistics.Numerical Operation like Addition, S
4 min read
Primitive Data Types vs Non Primitive Data Types in Python
Python, known for its versatility and user-friendliness, is a dynamic language that doesn't explicitly categorize data types into primitive and non-primitive as some languages like Java do. However, for clarity and understanding, it's useful to draw parallels and discuss similar concepts. In this article, we'll explore the types of data types tradi
4 min read
Does Dark Data Have Any Worth In The Big Data World?
Big Data is the new oil in modern times!!! And those companies that can analyze this data for actionable insights are the new super-rich!!! More and more companies are understanding this fact and investing in Big Data Analytics. So much so that this number has reached 53% in 2017, which is a huge growth from 17% in 2015. But Big Data is of multiple
5 min read
Training data vs Testing data
There are two key types of data used for machine learning training and testing data. They each have a specific function to perform when building and evaluating machine learning models. Machine learning algorithms are used to learn from data in datasets. They discover patterns and gain knowledge. make choices, and examine those decisions. In this ar
7 min read
Introduction to Simulation Modeling in Python
Simulation is imitating the operations which take place within a system to study its behavior. Analyzing and creating the model of a system to predict its performance is called simulation modeling. Simulation mimics a real-life process to determine or predict the response of the entire system. This helps to understand the dependency of each part of
4 min read
Introduction to Kivy ; A Cross-platform Python Framework
Kivy is an open-source, cross-platform Python framework used for developing multi-touch applications with a natural user interface. It allows developers to build applications that run on multiple platforms, including Windows, macOS, Linux, iOS, and Android. Kivy is based on the Model-View-Controller (MVC) architecture and uses a declarative languag
4 min read
Python | wxPython module Introduction
Python provides wxpython module which allows us to create high functional graphical user interface. It is an Open Source module, which means it is free for anyone to use and the source code is available for anyone to look and modify. It is implemented as a set of extension modules that wrap the GUI components of wxWidgets library which is written i
3 min read
Python | Introduction to PyQt5
There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. A GUI application consists of Front-end and Back
3 min read
Python sorted containers | An Introduction
Sorted Containers is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions. It was created by Grant Jenks and is an open source library. It is a collection of containers that allow us to insert and remove elements very efficiently while maintaining sorted order. Features: Pure-Python Fully documented Bench
6 min read
Introduction to pyglet library for game development in Python
Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc on Windows, Mac OS and Linux. This library is created purely in Python and it supports many features like windowing, user interface event handling, Joysticks, OpenGL graphics, loading images, and videos, and playing sounds and music.
2 min read
Introduction to Theory of Evolution in Python
The process of inheritance involves the transmission of characteristics from one generation to another in the form of genes. These genes actually have DNA which is the coded information about the characteristics. Due to inheritance, evolution takes place from one species to another. So we can conclude that evolution is a random process as it does n
2 min read
Introduction and Installation of Uberi/Speechrecognition in Python
One of the best library for speech recognition in Python and uses various engines and API to perform speech recognition online as well as offline. Installation Use this command in cmd or terminal make sure Python is installed and Python path is also stored in pc. pip install speechrecognition OR Download resources from PyPI and extract it in a fold
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg