Python · Level 3 OOP

Properties

Run code when an attribute is read or set with @property, to compute values on the fly and reject invalid ones.

  • @property for a computed attribute
  • @name.setter to validate assignments

@property makes a method look like an attribute. Add a .setter to run code, such as a check, whenever the attribute is assigned.

class Box:
    def __init__(self, cm):
        self.cm = cm

    @property
    def inches(self):
        return self.cm / 2.54

Box(254).inches     # 100.0  (no parentheses)

Complete Temperature: a fahrenheit property (celsius * 9 / 5 + 32) and a setter that updates celsius, raising ValueError below -459.67 °F.

solution.py
Test Suites Pending
Stdout