top

Search

Python Tutorial

The dataclasses module has been added in Python's standard library since version 3.7. It contains definition of @dataclass decorator an other functions that automatically generate constructor magic method __init__(), string representation method __repr__(), the __eq__() method which overloads == operator (and a few more) for a user-defined class.The dataclass function decorator carries following signature:dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)The arguments take a Boolean value and decide whether a corresponding magic method or methods will be automatically generated or not.The 'init' parameter is True by default which will automatically generate __init__() method for the class.Let us define Employee class using dataclass decorator as follows:from dataclasses import dataclass@dataclass class Employee(object):      name : str      age : int      salary : floatThe auto-generated __init__() method is like:def __init__(self, name: str, age: int, salary: float):        self.name = name        self.age = age        self.salary = salaryIf the class explicitly defines __init__() method, then auto-generation will not happen.The repr argument is true by default.  A __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. If the class already defines __repr__(), this parameter is ignored.The eq argument is by default true .The __eq__() method will be generated. This method gets called in response to equals comparison operator (==). If the class already defines __eq__(), this parameter is ignored.If the order is true (the default is False), __lt__(), __le__(), __gt__(), and __ge__() methods will be generated, they implement comparison operators < <= > ans >= respectively. If order is true and eq is false, a ValueError is raised. If the class already defines any of these methods), it results into TypeError.unsafe_hash argument if False (the default), a __hash__() method is generated according to how eq and frozen are set.frozen argument: If true (the default is False), emulates read-only frozen instances.>>> from data_class import Employee >>> e1=Employee('Naveen', 21, 2150.50) >>> e2=Employee('Mahesh', 20, 5000.00) >>> e1==e2 Falseasdict():This function converts class instance into a dictionary object.>>> import dataclasses >>> dataclasses.asdict(e1) {'name': 'Naveen', 'age': 21, 'salary': 2150.5}astuple():This function converts class instance into a tuple object.>>> dataclasses.astuple(e2) ('Mahesh', 20, 5000.0)make_dataclass():This function creates a new dataclass from the list of tuples given as fields argument.>>> NewClass=dataclasses.make_dataclass('NewClass', [('x',int),('y',float)]) >>> n=NewClass(10,20) >>> n NewClass(x=10, y=20)
logo

Python Tutorial

Python - Data Classes

The dataclasses module has been added in Python's standard library since version 3.7. It contains definition of @dataclass decorator an other functions that automatically generate constructor magic method __init__(), string representation method __repr__(), the __eq__() method which overloads == operator (and a few more) for a user-defined class.

The dataclass function decorator carries following signature:

dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

The arguments take a Boolean value and decide whether a corresponding magic method or methods will be automatically generated or not.

The 'init' parameter is True by default which will automatically generate __init__() method for the class.

Let us define Employee class using dataclass decorator as follows:

from dataclasses import dataclass

@dataclass
class Employee(object):
     name : str
     age : int
     salary : float

The auto-generated __init__() method is like:

def __init__(self, name: str, age: int, salary: float):
       self.name = name
       self.age = age
       self.salary = salary

If the class explicitly defines __init__() method, then auto-generation will not happen.

The repr argument is true by default.  A __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. If the class already defines __repr__(), this parameter is ignored.

The eq argument is by default true .The __eq__() method will be generated. This method gets called in response to equals comparison operator (==). If the class already defines __eq__(), this parameter is ignored.

If the order is true (the default is False), __lt__(), __le__(), __gt__(), and __ge__() methods will be generated, they implement comparison operators < <= > ans >= respectively. If order is true and eq is false, a ValueError is raised. If the class already defines any of these methods), it results into TypeError.

unsafe_hash argument if False (the default), a __hash__() method is generated according to how eq and frozen are set.

frozen argument: If true (the default is False), emulates read-only frozen instances.

>>> from data_class import Employee
>>> e1=Employee('Naveen', 21, 2150.50)
>>> e2=Employee('Mahesh', 20, 5000.00)
>>> e1==e2
False

asdict():

This function converts class instance into a dictionary object.

>>> import dataclasses
>>> dataclasses.asdict(e1)
{'name': 'Naveen', 'age': 21, 'salary': 2150.5}

astuple():

This function converts class instance into a tuple object.

>>> dataclasses.astuple(e2)
('Mahesh', 20, 5000.0)

make_dataclass():

This function creates a new dataclass from the list of tuples given as fields argument.

>>> NewClass=dataclasses.make_dataclass('NewClass', [('x',int),('y',float)])
>>> n=NewClass(10,20)
>>> n
NewClass(x=10, y=20)

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Eula

This is my first time here. I am truly impressed to read all this in one place.

Jaypee Dela Cruz

Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!

lucky verma

Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.

Pre Engineered Metal Building

Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.

Pre Engineered Metal Building

Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More