Flexible Data Classes

We already discussed some methods to make dataclasses and now we’ll study some more advanced features like parameters to a @dataclass decorator. Adding parameters to a dataclass provides us with more control when creating a data class.

Example:

Python3




# import package
from dataclasses import dataclass
from typing import List
  
# make a dataclass with decorator
@dataclass
class DataClassGFG:
    Job: str
    Salary: float
          
@dataclass
class GFGJobs:
    Jobs: List[DataClassGFG]
  
# make objects with values required by dataclass
DataClassObject1 = DataClassGFG("Author",50000.00)
DataClassObject2 = DataClassGFG("Writer",40000.00)
  
# view dataclass objects
print(DataClassObject1)
print(DataClassObject2)
  
# make an object of another dataclass
GFGJobsObject = GFGJobs([DataClassObject1,DataClassObject2])
  
# view dataclass object
print(GFGJobsObject)


Output:

DataClassGFG(Job=’Author’, Salary=50000.0)

DataClassGFG(Job=’Writer’, Salary=40000.0)

GFGJobs(Jobs=[DataClassGFG(Job=’Author’, Salary=50000.0), DataClassGFG(Job=’Writer’, Salary=40000.0)])

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. 

Similar Reads

Basic Data Classes

The following ways show how a basic data class can be created:...

Immutable Data Classes

...

Flexible Data Classes

...

Optimizing Data Classes

...