You could use an approach with @property decorator, as mentioned, and turn all dataclass fields into field properties:
from dataclasses import dataclass
from datetime import datetime, date
@dataclass(kw_only=True)
class ChildTestProduct:
t1: float
t2: datetime | str
@property
def t1(self) -> str:
return f'{self._t1:.2f}€'
@t1.setter
def t1(self, value: float):
self._t1 = value
@property
def t2(self) -> str:
return self._t2.strftime('%m/%d/%Y')
@t2.setter
def t2(self, value: datetime | str):
if isinstance(value, str):
self._t2 = datetime.strptime(value, '%m/%d/%y').date()
else:
self._t2 = value
p = ChildTestProduct(t1=99.9, t2='10/8/22')
print(p) # ChildTestProduct(t1='99.90€', t2='10/08/2022')
assert isinstance(p._t1, float)
assert isinstance(p._t2, date)
t1is99.9(float), when do you want it to become"99.90€"(string)?99.9€or a float 7.893217854? also would a string be pass in to date value so ilke 02/08/10 for example?@propertydecorator so that setting the instance attributes programmatically defines your attributes the way you want. With properties, you can even store a true value and return a formatted value with the attribute getter.