Overview
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
Short Course
@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)
Task
Complete Temperature: a fahrenheit property (celsius * 9 / 5 + 32) and
a setter that updates celsius, raising ValueError below -459.67 °F.
Test Suites
Pending
Stdout