#!/usr/bin/python3 # ==================================================================== # from: www.youtube.com/watch?v=y1ZWQQEe5PM # 5 Useful Dunder Methods In Python # ==================================================================== # ---- class definition ---------------------------------------------- class Fruit: def __init__(self, *, name: str, grams: float) -> None: self.name = name self.grams = grams def __format__(self, format_spec: str) -> str: match format_spec: case 'kg': return f'{self.grams/1000:.2f}kg of {self.name}' case 'lb': return f'{self.grams/453.5924:.2f}lb of {self.name}' case 'g': return f'{self.grams}g of {self.name}' case _: raise ValueError('Unknown format specified...') # ---- main ---------------------------------------------------------- def main() -> None: apple: Fruit = Fruit(name="Apple",grams=2500) print(f'{apple:kg}') # -------------------------------------------------------------------- # ---- main # -------------------------------------------------------------------- if __name__ == '__main__': main()