Temperature with Properties
Write a class Temperature(celsius) that stores one temperature and offers it in two scales:
- a property
celsiusthat can be read and set, - a property
fahrenheitthat can be read and set; it is always consistent withcelsius(F = C * 9 / 5 + 32), - a temperature below absolute zero (-273.15 degrees Celsius) is not allowed: creating one, or setting
celsiusorfahrenheitto one, raisesValueError, 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?
- Two, one for each scale
- One: the other is computed when asked
- 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.)
VISIBLE = 3
CASES = [
('result = Temperature(100).fahrenheit', 212.0, 'Celsius to Fahrenheit'),
('t = Temperature(0)\nt.fahrenheit = 212\nresult = t.celsius', 100.0, 'setting Fahrenheit changes Celsius'),
('result = error_of(Temperature, -300)', 'ValueError', 'below absolute zero at creation'),
('t = Temperature(20)\nt.celsius = 25\nresult = t.celsius', 25, 'setting Celsius'),
('t = Temperature(20)\nerror_of(setattr, t, "celsius", -500)\nresult = t.celsius', 20, 'a rejected value leaves the old one'),
('t = Temperature(20)\nerror_of(setattr, t, "fahrenheit", -1000)\nresult = t.celsius', 20, 'a rejected Fahrenheit value leaves the old one'),
('result = Temperature(-273.15).celsius', -273.15, 'absolute zero is allowed'),
('t = Temperature(37)\nresult = round(t.fahrenheit, 1)', 98.6, 'body temperature'),
('t = Temperature(10)\nt.celsius = 30\nresult = t.fahrenheit', 86.0, 'the two views stay consistent'),
]