Dataclasses
Anotation @dataclasses
is just like @AllArgsConstructor
in java
For example:
from dataclasses import dataclass, field
from typing import *
@dataclass
class Node:
value: int = 0
left: 'Node' = field(init=False, default=None)
right: 'Node' = field(init=False, default=None)
if __name__ == "__main__":
root = Node()
root.left = Node(5)
root.right = Node(10)
print(root)
We will have this:
Node(value=0, left=Node(value=5, left=None, right=None), right=Node(value=10, left=None, right=None))
@dataclass
will add for us repr
which will print out the corresponding value of a node.
Also for left
and right
, since we don't want it to be in constructor, we need to use field()
and marks init=False
. '
However when marking init=False
we also need to state that default=None
.