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. 

Basic Data Classes

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

1. Using decorator: They are created using the new @dataclass decorator.

Example: 



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import package
from dataclasses import dataclass
  
# make a dataclass with decorator
@dataclass
class DataClassGFG:
    Job: str
    Salary: float
  
# make an object with values required by dataclass
DataClassObject = DataClassGFG("Author",50000.00)
  
# view dataclass object
print(DataClassObject)

chevron_right


Output:

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

2. Using make_dataclass():

Example: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import package
from dataclasses import make_dataclass
  
# make a dataclass with make_dataclass
  
DataClassGFG = make_dataclass("DataClassGFG",["Job","Salary"])
  
# make an object with values required by dataclass
DataClassObject = DataClassGFG("Author",50000.00)
  
# view dataclass object
print(DataClassObject)

chevron_right


Output:

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



3. Using namedtuple: Using namedtuple() method from collections. The is just similar to make_dataclass().

Example: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import package
from collections import namedtuple
  
# make a dataclass with namedtuple
  
DataClassGFG = namedtuple("DataClassGFG",["Job","Salary"])
  
# make an object with values required by dataclass
DataClassObject = DataClassGFG("Author",50000.00)
  
# view dataclass object
print(DataClassObject)

chevron_right


Output:

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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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"

chevron_right


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’
 

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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)])

Optimizing Data Classes

For optimizing the data classes we use slots. Slots are often used to make classes faster and use less memory. Data classes don’t have any explicit syntax for working with slots, but the traditional way of making slots works for data classes also.

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import package
from dataclasses import dataclass
  
# make a dataclass with decorator
@dataclass
class DataClassGFG:
    Job: str
    Salary: float
          
@dataclass
class SlotClassGFG:
    __slots__ = ["Job","Salary"]
    Job: str
    Salary: float
  
# make objects with values required by dataclass
DataClassObject1 = DataClassGFG("Author",50000.00)
DataClassObject2 = SlotClassGFG("Writer",40000.00)
  
# view dataclass objects
print(DataClassObject1)
print(DataClassObject2)
  
# view dataclass object slot
print(DataClassObject2.__slots__)

chevron_right


Output:

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

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

[‘Job’, ‘Salary’]

Inheritance

We can simply use the concept of inheritance by creating sub data class of a data class. 



Example: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import package
from dataclasses import dataclass
  
# make a dataclass with decorator
@dataclass
class DataClassGFG:
    Job: str
    Salary: float
          
@dataclass
class SubDataClassGFG(DataClassGFG):
    Standard: str = "Top"
    Salary: float = 100000.00
  
  
# make objects with values required by dataclass
DataClassObject1 = DataClassGFG("Author",100000.00)
DataClassObject2 = DataClassGFG("Author",50000.00)
  
# view dataclass objects
print(DataClassObject1)
print(DataClassObject2)
  
# make object with values required by subdataclass
SubDataClassObject = SubDataClassGFG("Author")
  
# view subdataclass object
print(SubDataClassObject)

chevron_right


Output:

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

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

SubDataClassGFG(Job=’Author’, Salary=100000.0, Standard=’Top’)

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.