Python data classesWhat are they? How to use them?
Let's find out
There's really nothing special about the class: the dataclass decorator adds generated methods- __init__
- __repr__
- __eq__
to the class and returns the same class it was given.
Generated __init__ method takes all fieldsas function parameters. Their values are set to instance attributes with the same names.
For example, you can define User with fields id and name.
Generated __repr__ method returns a string containing:- class name
- field names
- field representation
The order of fields is the same as the order of their definition in a class
Generated __eq__ method compares the class tuples containing field values of the current and the other instance.It supports only instances of the same class
True is returned if:
- current and other are of the same class
- fields of both have the same values
For example
You can enable order by setting the order argument of the decorator to True.It adds methods:
- __lt__
- __le__
- __gt__
- __ge__
They are implemented in the same way as __eq__
You can make instances immutable by setting the argument frozen to TrueIn such case dataclasses.FrozenInstanceError is raised if you try to reassign instance attribute
You can use __post_init__ hook on data classes to set the value of the attribute based on the others' values
You can read more:https://www.python.org/dev/peps/pep-0557/
https://docs.python.org/3/library/dataclasses.html#module-dataclasses
Read on Twitter