guides
Property Descriptors
@property, @cached_property, and custom descriptors.
Published May 30, 2026
@property
class Rectangle:
def __init__(self, width: float, height: float):
self._width = width
self._height = height
@property
def area(self) -> float:
return self._width * self._height
@property
def perimeter(self) -> float:
return 2 * (self._width + self._height)
@cached_property
from functools import cached_property
class DataSet:
def __init__(self, raw: list[float]):
self.raw = raw
@cached_property
def mean(self) -> float:
return sum(self.raw) / len(self.raw)
@cached_property
def variance(self) -> float:
m = self.mean
return sum((x - m) ** 2 for x in self.raw) / len(self.raw)