Properties in Python
Attribute syntax with method power: computed and guarded fields.
class Temperature:
def __init__(self, celsius=0):
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
How it works
@propertymakescelsiusreadable like a plain attribute.- The setter validates before storing.
fahrenheitis computed fresh on every read.
Keywords and builtins used here
Temperaturecelsiusclassdeffahrenheitifraisereturnself
The run, in numbers
- Lines
- 17
- Characters to type
- 316
- Tokens
- 75
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 47 seconds.
Step 3 of 5 in Classes, step 41 of 72 in Language basics.