Python 3D Academyবাংলা

@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 @property that works the value out
  • read-only: a property with only a getter can't be set

Step by step, for rect.area:

  1. Python finds area in the class and sees it's a property.
  2. It runs the getter with self = rect: self.width * self.height.
  3. The answer comes back as if it were a stored value.

Why not just store the area? Because stored values go stale:

  1. you make Rectangle(2, 3) and save self.area = 6
  2. later someone sets rect.width = 10
  3. rect.area still 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 date
@property goes on the line just above the def. The method takes only self.

Properties are great for things that are made from other attributes:

  • a person's full_name from first and last name
  • a temperature in Fahrenheit from Celsius
  • a cart's total from 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")
adding up... appears once: the second read used the stored 250. After a new sale the cached total is out of date.

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 = 5 gives AttributeError: 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, like self._area.

Quiz

  1. 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)
  2. How do you read a property called area?

    • r.area
    • r.area()
    • area(r)
  3. 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)
  4. 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
  5. 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())
  6. 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

  1. Give Rectangle a property area (width × height). It must stay right after the width or height changes.

  2. Write a class Person(first, last) with a property full_name that gives the first and last name with a space between.

  3. Write a class Temperature(celsius) with a property fahrenheit, worked out as celsius × 9 / 5 + 32.