Introduction
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.
Classes Recap:
- What is a class ?
it can simply be defined as an object constructor or a blueprint of creating an object.
Example
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
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.
NB:
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.
DataClasses
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
automatically.
Example 1:
Consider the example of Student object created above, but now modified.
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
def greet_student(self) -> str:
return f'Hello {self.name}, you are {self.age} years old'
p = Student('Tito',16)
print(p.greet_student())
Output:
Hello Tito, you are 16 years old
Example 2:
from dataclasses import dataclass
@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
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.
Top comments (0)