Python Dataclasses

Part 1: Introduction

Part 2: A Data Class Without Initialization

@dataclass(order=True)
class Number:
name:str="my_name"
val:int=10
  • order=True defines __eq__ and __lt__ automatically
  • val:int=10 variable, its type, and its initialization value
  • class object variable is initialized according to its definition sequence, e.g., Number('my_name", 34)

Part 3: Frozen Variable

@dataclass(frozen = True)
class Number:
val: int = 0

Part 4: A Data Class with Initialization

  • dataclasses.field accepts a default_factory argument which can be used to initialize the field if a value is not passed at the time of creation of the object. default_factory should be a callable( generally a function ) which accepts no arguments.
  • dataclasses.field accepts a defaul argument.
  • field(compare = False)
  • field(repr=False)
  • field(defaut=False)

Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store