@property: values that work themselves out
🌍 In real life. A car's dashboard shows "range: 320 km". Nobody types that number in: the car works it out from the fuel left and how much it uses, every time you look. You just read it, like any other number on the dashboard.
A property is that dashboard number for an object. It looks like a plain attribute (rect.area, no brackets), but behind it a method runs and works the answer out fresh.
The idea in one sentence: @property turns a method into something you read like an attribute, rect.area with no brackets, worked out fresh each time.
Its words:
- property: a method that looks like an attribute
- getter: the method under
@propertythat works the value out - read-only: a property with only a getter can't be set
Step by step, for rect.area:
- Python finds
areain the class and sees it's a property. - It runs the getter with
self=rect:self.width * self.height. - The answer comes back as if it were a stored value.
Why not just store the area? Because stored values go stale:
- you make
Rectangle(2, 3)and saveself.area = 6 - later someone sets
rect.width = 10 rect.areastill says 6, which is now wrong
A property never goes stale, because it's worked out at the moment you read it.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
r = Rectangle(2, 3)
print(r.area) # no brackets: it reads like an attribute
r.width = 10
print(r.area) # worked out again, so it's up to dateProperties are great for things that are made from other attributes:
- a person's
full_namefrom first and last name - a temperature in Fahrenheit from Celsius
- a cart's
totalfrom its items
A property with only a getter is read-only: trying to set it raises an AttributeError, which protects the value from being changed by mistake.
class Person:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def full_name(self):
return self.first + " " + self.last
p = Person("Ada", "Lovelace")
print(p.full_name)
try:
p.full_name = "Someone Else"
except AttributeError as e:
print("Can't set it:", e)Work it out once: cached_property. When a value is slow to work out and won't change, @cached_property from functools runs the method on the first read, then stores the answer on the object; later reads take the stored value without running anything. The catch is the one that properties avoid: if the data it was made from changes, the cached value goes stale. Use it for values that are fixed once the object is made.
from functools import cached_property
class Report:
def __init__(self, sales):
self.sales = sales
@cached_property
def total(self):
print("adding up...")
return sum(self.sales)
r = Report([120, 80, 50])
print(r.total)
print(r.total)
r.sales.append(100)
print(r.total, "<- stale: the 100 is missing")What it costs. A property runs its method every time you read it, so keep it quick. A property that sums a long list is still a loop on every read.
Mistakes and edge cases.
- Calling it with brackets.
rect.area()runs the getter, then tries to call the number:TypeError: 'int' object is not callable. - Setting a read-only property.
p.area = 5givesAttributeError: property 'area' of 'P' object has no setter. - Returning self.area inside the getter. That reads the property again, forever:
RecursionError: maximum recursion depth exceeded. Store the real value under another name, likeself._area.
Quiz
What does this print?
class Square: def __init__(self, side): self.side = side @property def area(self): return self.side * self.side s = Square(3) s.side = 4 print(s.area)How do you read a property called
area?- r.area
- r.area()
- area(r)
What does this print?
class Cart: def __init__(self): self.prices = [] @property def total(self): return sum(self.prices) c = Cart() c.prices.append(50) c.prices.append(30) print(c.total)A property has a getter but no setter. What happens on
obj.prop = 5?- An AttributeError: the property is read-only
- The property becomes 5
- Nothing happens
Which line has a mistake?
class Circle: def __init__(self, radius): self.radius = radius @property def diameter(self): return self.radius * 2 c = Circle(5) print(c.diameter())When is @cached_property a better fit than @property?
- When the value is slow to work out and the data it comes from never changes
- When the value must always be up to date
- When the value should be changeable with =
Coding tasks
Give
Rectanglea propertyarea(width × height). It must stay right after the width or height changes.Write a class
Person(first, last)with a propertyfull_namethat gives the first and last name with a space between.Write a class
Temperature(celsius)with a propertyfahrenheit, worked out as celsius × 9 / 5 + 32.