Immutable Data Classes
One of the defining features of the namedtuple we saw earlier is that it’s immutable i.e., the value of its fields may never change. For several sorts of data classes, this is often an excellent idea to create an immutable class and to achieve this just simply set frozen=True once you create it.
Example:
Python3
# import package from dataclasses import dataclass # make a dataclass with decorator @dataclass (frozen = True ) class DataClassGFG: Job: str Salary: float # make an object with values required by dataclass DataClassObject = DataClassGFG( "Author" , 50000.00 ) # view dataclass object print (DataClassObject) # check immutable nature of class DataClassObject.Job = "Writer" |
Output:
DataClassGFG(Job=’Author’, Salary=50000.0)
Traceback (most recent call last):
File “main.py”, line 17, in <module>
DataClassObject.Job = “Writer”
File “<string>”, line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field ‘Job’
The Ultimate Guide to Data Classes in Python 3.7
This article discusses data classes in Python 3.7 and provides an introductory guide for data classes in Python 3.7 and above.
Data Class is a new concept introduced in Python 3.7 version. You can use data classes not only as a knowledge container but also to write boiler-plate code for you and simplify the process of creating classes since it comes with some methods implemented for free. A data class could also be considered as a category typically containing data, but they aren’t limited to that.