29. Temperature with Properties
Difficulty: Easy · Topic: OOP & classes
Write a class Temperature(celsius) with two properties:
celsius: read and write. A value below absolute zero,-273.15, raisesValueError, whether it comes from the constructor or a later assignment.fahrenheit: read and write, always consistent withcelsius(F = C × 9 / 5 + 32). Setting it changescelsius, with the same check.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
t = Temperature(25)
t.fahrenheitExpected: 77.0
Hints
Hint 1
Store a single value (Celsius) and compute the other: two stored values can drift apart.Hint 2
@celsius.setter defines what t.celsius = x does.Hint 3
Let the constructor assign through the property (self.celsius = celsius) so the check lives in one place.Learn the concepts
- Classes, properties and dataclasses · 4 min read. Invariants, validated and read-only attributes, alternate constructors and record types.
More Python problems
- Bank Account with Validation · Easy
- Build Records from CSV Rows · Medium
- An Abstract Connector Class · Medium
- A Comparable Version Class · Medium
- LRU Cache · Hard
- A Transaction Context Manager · Hard