Medium: Interview Core · Problem 48 of 82

Temperature with Properties

MediumClassesPython

Write a class Temperature(celsius) that stores one temperature and offers it in two scales:

  • a property celsius that can be read and set,
  • a property fahrenheit that can be read and set; it is always consistent with celsius (F = C * 9 / 5 + 32),
  • a temperature below absolute zero (-273.15 degrees Celsius) is not allowed: creating one, or setting celsius or fahrenheit to one, raises ValueError, and the old value stays.

Understand the problem

Think about where the value lives.

Two properties show the same temperature. How many numbers should the object store?

  1. Two, one for each scale
  2. One: the other is computed when asked
  3. Zero

Storing both would let them disagree. Store one value (Celsius) and compute the other in its property. There is then only one source of truth.

What is 100 degrees Celsius in Fahrenheit? (100 * 9 / 5 + 32)

100 x 9 / 5 = 180, and 180 + 32 = 212. Setting fahrenheit needs the opposite formula: C = (F - 32) * 5 / 9.

Write the solution

Write the class with two properties and setters.

class Temperature:
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Where should the validation live, so that every way of setting the value is checked, including the constructor?

Hint 2: the shape of the answer

Store self._celsius. The celsius setter validates and assigns. __init__ sets self.celsius = celsius (not _celsius) so the setter runs. The fahrenheit setter converts and assigns through self.celsius.

Reflect

Solution

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._celsius = value

    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        self.celsius = (value - 32) * 5 / 9

What this tests: properties with @property and @name.setter, validation in one place, and computed attributes.

Assign through the property in __init__. self.celsius = celsius runs the setter, so the constructor gets the same validation for free. Writing self._celsius = celsius would skip it, and Temperature(-500) would be accepted.

Single source of truth: fahrenheit is derived, never stored. Derived values that are stored can go out of date.

The old value stays on error: the setter raises before assigning, so a rejected assignment leaves the object unchanged.

Floats: (212 - 32) * 5 / 9 is exactly 100.0, but other conversions have rounding error. Tests (and code) should compare with a tolerance (math.isclose).

What an interviewer might ask next: Add a read-only property kelvin. (celsius + 273.15, with no setter.)