Since python 3.7 there is a new built in module called dataclasses which has the dataclass class in it.
Pycharm supports it and knows how to work with it.
It is a perfect fit for a value object, since it already defines a lot of what you would define for a value object and the syntax is really short:
- repr
- eq
making the class immutable by passing Frozen=True
example:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point2D:
x: float
y: float
There are differences between NamedTuple and Dataclasses which most notably one is based on a tuple and the other one on a dict.
In my opinion, the dataclass is the best code generator ATM to create a value object.
For more info, continue with python’s docs about how to use a dataclass.
官方文档:https://docs.python.org/3.7/library/dataclasses.html
https://docs.python.org/3.7/library/collections.html?highlight=namedtuple#collections.namedtuple