Jun-25-2021, 12:09 PM
Hi there
I have a class
I have a class
PrintValue
that contains as attribute an instances of another class PrintMetaData
. In order to acess an attribute of the PrintMetaData
object I would have to do something like object.meta_data.attribute
. I wanted to flatten the access to the attribute to object.attribute
. I wrote a class to do that and was wondering if that is considered bad practice. Obviously there is the possibility of name conflicts if the classes have attributes with the same name, but I could live with that. Here an example:from dataclasses import dataclass @dataclass class PrintMetaData: """Print meta data for attr.""" long: str abbr: str unit: str = None round_precision: int = 2 @dataclass class PrintValue: """Printer wrapper for value.""" value: float meta_data: PrintMetaData def __getattr__(self, name): try: return getattr(self.meta_data, name) except AttributeError: return self.__getattribute__(name) fwd_perp_md = PrintMetaData( "Foward perpendicular", r"F\textsubscript{P}", "m" ) fwd_perp_value = PrintValue(10, fwd_perp_md) print(fwd_perp_value.meta_data) print(fwd_perp_value.long) print(fwd_perp_value.abbr) print(fwd_perp_value.unit) print(fwd_perp_value.round_precision)This is small and seems to work, but I was wondering if that is still ok with classes with more internal objects.