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.
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.
Named Tuple is essentially an extension of the Python built-in tuple data type. Python’s tuple is a simple data structure for grouping objects with different types. Its defining feature is being immutable i.e an object whose state cannot be modified after it is created.
We will start with the collections package. This package provides alternatives to Python’s general built-in types like dict, list, set, and tuple. Creating a NamedTuple object is as straightforward as creating the class.
Transaction(sender=’Aryaman’, amount=1.0, receiver=’Ankur’, date=’2020-06-18′)
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.
Transaction(sender=’Aryaman’, receiver=’Ankur’, date=’2020-06-18′, amount=1.0)
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course