Mar-04-2022, 09:52 PM
(This post was last modified: Mar-04-2022, 10:03 PM by deanhystad.)
Nice! Adding a units enumeration makes this a lot more flexible. To add a new unit all I need to do is add it to the enumeration and provide equations for converting to and from Celsius.
import enum class Temperature: """I am a temperature. You can specify my units. I do unit conversion""" class Unit(enum.Enum): CELSIUS = "C" FAHRENHEIT = "F" KELVIN = "K" # Convert from unit to Celsius convert_from = { Unit.CELSIUS: lambda x: x, Unit.KELVIN: lambda x: x - 273.15, Unit.FAHRENHEIT: lambda x: (x - 32) * 5 / 9 } # convert from Celsius to unit convert_to = { Unit.CELSIUS: lambda x: x, Unit.KELVIN: lambda x: x + 273.15, Unit.FAHRENHEIT: lambda x: (x * 9) / 5 + 32 } def __init__(self, value=None, unit=Unit.CELSIUS): self.units = unit self.set(0 if value is None else value) def set(self, value, unit=None): """Set temperature value. Can specify unit for value.""" if unit is None: unit = self.units self.degreesC = self.convert_from[unit](value) return self.degreesC def set_units(self, units): """Change the default temperature units""" self.units = units def get(self, unit=None): """Get temperature value. Can specify unit for value.""" if unit is None: unit = self.units return self.convert_to[unit](self.degreesC) def __str__(self): """Get str for printing.""" return f"{self.get()} °{self.units.value}" temp = Temperature(273.15, Temperature.Unit.KELVIN) print("Converting", temp) for unit in Temperature.Unit: temp.set_units(unit) print(f"to {unit.name} {temp}")
Output:Converting 273.15 °K
to CELSIUS 0.0 °C
to FAHRENHEIT 32.0 °F
to KELVIN 273.15 °K