typestar

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

  1. @property makes celsius readable like a plain attribute.
  2. The setter validates before storing.
  3. fahrenheit is computed fresh on every read.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Classes, step 41 of 72 in Language basics.

← Previous Next →