Creating Classes with a More Compact Syntax
Learn how to make use of dataclasses decorator to create classes with compact syntax.
Let's continue with the idea that sometimes, we need objects to hold values. There's a common boilerplate in Python when it comes to the initialization of objects, which is to declare in the __init__
method all attributes that the object will have, and then set that to internal variables, typically in this form:
def __init__(self, x, y, ...):self.x = xself.y = y
The dataclasses
module
Ever since Python 3.7 was released, we can simplify this by using the dataclasses
module.
The @dataclass
decorator
This module provides a @dataclass
decorator, which, when applied to a class, will take all the __init__
method on the class, so we don't have to. ...