DEV Community

Cover image for Python: Introduction to DataClasses

Posted on • Updated on

Python: Introduction to DataClasses


This article will be explaining the concept of data class introduced in python 3.7+.My assumption are you are conversant with python in particular object-oriented Programming. However, I will briefly explain the concept and redirect you to more resources.see PEP 557

Classes Recap:

  • What is a class ?

it can simply be defined as an object constructor or a blueprint of creating an object.


class Student:
  def __init__(self, name, age): = name
    self.age = age
Enter fullscreen mode Exit fullscreen mode

line 1: class definition with the name of the object (Student).
line 2 to 4: Object constructor.The init() function is called automatically every time the class is being used to create a new object.


The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class.


The new dataclass() decorator provides a way to declare data classes. A data class describes its attributes using class variable annotations. Its constructor and other magic methods, such as repr(), eq(), and hash() are generated

Example 1:

Consider the example of Student object created above, but now modified.

from dataclasses import dataclass
class Student:
  name: str
  age: int
  def greet_student(self) -> str:
    return f'Hello {}, you are {self.age} years old'
p = Student('Tito',16)
Enter fullscreen mode Exit fullscreen mode
Hello Tito, you are 16 years old
Enter fullscreen mode Exit fullscreen mode

Example 2:

from dataclasses import dataclass

class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand
Enter fullscreen mode Exit fullscreen mode

From the above example, you will notice we have omitted the init() constructor , data class will added it automatically. Data class will help you create object easily and add more configurations to your objects.Now that you have a basic understanding of data classes in python. In our next episode I will be diving deep into data classes concepts.
Follow for more content.

Buy Me a coffee

Top comments (0)