Dataclasses
Learn about the concept of dataclasses in Python.
We'll cover the following...
Since Python 3.7, dataclasses let us define ordinary objects with a clean syntax for specifying attributes. They look very similar to named tuples. This is a pleasant approach that makes it easy to understand how they work.
Example
Here’s a dataclass
version of our Stock
example:
from dataclasses import dataclass@dataclassclass Stock:symbol: strcurrent: floathigh: floatlow: float
For this case, the definition is nearly identical to the NamedTuple
definition.
The dataclass
function is applied as a class decorator, using the @
operator.
This class definition syntax isn’t much less verbose than an ordinary class with __init__()
, but it gives us access to several additional dataclass
features.
It’s important to recognize that the names are provided at the class level but are not actually creating class-level attributes. The class-level names are used to build several methods, including the __init__()
method; each instance will have the expected attributes. The decorator ...