How to use DataClass In Python
DataClass may be a new feature introduced since Python 3.7. It is used as a decorator. What it does under the hood is implementing __init__, __repr__, etc for us.
Example:
Python3
from dataclasses import dataclass @dataclass class Transaction: sender: str receiver: str date: str amount: float # Creating object record = Transaction(sender = "Aryaman" , receiver = "Ankur" , date = "2020-06-18" , amount = 1.0 ) print (record) print (record.receiver) |
Output:
Transaction(sender=’Aryaman’, receiver=’Ankur’, date=’2020-06-18′, amount=1.0)
Ankur
NamedTuple behaves like a tuple, while DataClass behaves more like a regular Python class because by default, the attributes are all mutable and they can only be accessed by name, not by index.
How to use NamedTuple and Dataclass in Python?
We have all worked with classes and objects for more than once while coding. But have you ever wondered how to create a class other than the naive methods we have all been taught. Don’t worry in this article we are going to cover these alternate methods. There are two alternative ways to construct a class in Python.
First, of all let’s create a class with the naive methods. Let’s create a class transaction, where each payment transaction has a sender, a receiver, date, and the amount.
Example:
Python
class Transaction: def __init__( self , amount, sender, receiver, date): self .amount = amount self .sender = sender self .receiver = receiver self .date = date |
This is pretty straight forward but let’s be honest this is a lot of code for us lazy developers. Now, this is where NamedTuple comes in.