[docs]classSerialMixin:"""A mixin class providing serialization functionality."""# Use slots so that derived classes also remain slotted# See also: https://www.attrs.org/en/stable/glossary.html#term-slotted-classes__slots__=()
[docs]defto_dict(self)->dict:"""Create an object's dictionary representation. Returns: The dictionary representation of the object. """dct=converter.unstructure(self)return_add_type_to_dict(dct,self.__class__.__name__)
[docs]@classmethoddeffrom_dict(cls:type[_T],dictionary:dict)->_T:"""Create an object from its dictionary representation. Args: dictionary: The dictionary representation. Returns: The reconstructed object. """returnconverter.structure(dictionary,cls)
[docs]defto_json(self)->str:"""Create an object's JSON representation. Returns: The JSON representation as a string. """returnjson.dumps(self.to_dict())
[docs]@classmethoddeffrom_json(cls:type[_T],string:str)->_T:"""Create an object from its JSON representation. Args: string: The JSON representation of the object. Returns: The reconstructed object. """returncls.from_dict(json.loads(string))