Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Introduction to Python GIS
Next article icon

Data Classes in Python | An Introduction

Last Updated : 23 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
 



Next Article
Introduction to Python GIS
author
vibhu4agarwal
Improve
Article Tags :
  • Python
  • python-modules
Practice Tags :
  • python

Similar Reads

  • Python Introduction
    Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code. Key Features of PythonPython’s simple and readable syntax makes it beginner-frie
    3 min read
  • Introduction to Python GIS
    Geographic Information Systems (GIS) are powerful tools for managing, analyzing, and visualizing spatial data. Python, a versatile programming language, has emerged as a popular choice for GIS applications due to its extensive libraries and ease of use. This article provides an introduction to Pytho
    4 min read
  • Introduction to Python for Absolute Beginners
    Are you a beginner planning to start your career in the competitive world of Programming? Looking resources for Python as an Absolute Beginner? You are at the perfect place. This Python for Beginners page revolves around Step by Step tutorial for learning Python Programming language from very basics
    6 min read
  • Input and Output in Python
    Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
    8 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
    2 min read
  • FastAPI - Introduction
    Developers are continuously on the lookout for technologies that allow them to rapidly and efficiently construct sophisticated APIs and online applications. FastAPI, a relatively new addition to the Python web framework landscape, has quickly garnered traction due to its speed, simplicity, and devel
    5 min read
  • First Class functions in Python
    First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
    2 min read
  • Interact with files in Python
    Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complica
    6 min read
  • Introduction to JustPy | A Web Framework based on Python
    JustPy is a web framework that leverages the power of Python to create web applications effortlessly. In this article, we'll explore JustPy, its features, and why it's gaining attention among developers. What is the JustPy Module of Python?The JustPy module of Python is a web framework like Django b
    8 min read
  • Creating nested dataclass objects in Python
    Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special method
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences