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@dataclassclass 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)
Rated 5/5 based on 11 customer reviews
logo

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 : 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 *

Suggested Tutorials

C# Tutorial

By KnowledgeHut

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.
Rated 5/5 based on 12 customer reviews
C# Tutorial

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

Read More