Methods & Properties — Python

A decorator @... above a def changes how the method is used. @property lets you read a method like an attribute, without brackets (coffee.label), and its…

Write coffee.price = -3, and Python says nothing. No error, no warning. Tomorrow the receipt shows coffee with milk at minus three dollars. A plain attribute accepts any value you give it.

The price board at Mr. Darto's stall does not accept just any number, because a cashier guards it. Anyone may write a new price on the board. But every time someone does, the cashier checks it first: a negative price? Refused. A customer who reads the board doesn't know there is a cashier behind it. A property works like that price board. From outside, a property looks like a plain attribute: that is the board. But every time its value is read or written, a method runs behind it: that is the cashier. Besides ordinary methods that use self, a Python class has three more tools:

Decorators and four kinds of method

A decorator is an @name line right above a def. It changes how the method below it is used, without changing what is inside it. This table compares the four kinds of method. The sections below explain each example:

Kind How to write it First parameter How to call it
Ordinary method (instance method) def total(self, quantity): self, the object coffee.total(3)
Property @property above the def self coffee.label, no brackets
Class method @classmethod above the def cls, the class Menu.from_text("toast,12")
Static method @staticmethod above the def none Menu.discount(89)

@property: an attribute that is computed

In this class, label is written as a method, with @property above it:

class Menu:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    @property
    def label(self):
        return f"{self.name} ({self.price})"

coffee = Menu("coffee with milk", 15)
print(coffee.label)     # coffee with milk (15)
coffee.price = 17
print(coffee.label)     # coffee with milk (17)

A setter that guards the value

A setter is a method that runs every time a property is given a new value: the cashier who checks a number before it goes on the board. In this class, the setter refuses a negative price:

class Menu:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("price cannot be negative")
        self._price = value

coffee = Menu("coffee with milk", 15)
coffee.price = 17
print(coffee.price)     # 17
coffee.price = -5

The output:

17
Traceback (most recent call last):
  File "/home/darto/stall.py", line 19, in <module>
    coffee.price = -5
    ^^^^^^^^^^^^
  File "/home/darto/stall.py", line 13, in price
    raise ValueError("price cannot be negative")
ValueError: price cannot be negative

@staticmethod and @classmethod

This class has one class method, from_text, and one static method, discount:

class Menu:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    @classmethod
    def from_text(cls, text):
        name, price = text.split(",")
        return cls(name, int(price))

    @staticmethod
    def discount(total):
        if total >= 100:
            return 15
        elif total >= 50:
            return 10
        elif total >= 25:
            return 5
        return 0

toast = Menu.from_text("toast,12")
print(toast.name, toast.price)   # toast 12
print(Menu.discount(89))         # 10
print(toast.discount(120))       # 15

⚠️ Too many brackets, and a setter that calls itself

TL;DR: A decorator @... above a def changes how the method is used. @property lets you read a method like an attribute, without brackets (coffee.label), and its value is computed again on every read. Calling it with brackets gives TypeError: 'str' object is not callable. @price.setter makes a setter: a method that runs when coffee.price = ... is written. A setter can refuse a value with raise ValueError(...), and it keeps the number in self._price. self.price = price in __init__ goes through the setter too, so a negative price is refused when the object is made. @staticmethod receives neither self (the object) nor cls (the class), and is good for helper functions such as discount(total). @classmethod receives cls (the class) and is often used as an alternative constructor (another way to make an object) such as Menu.from_text(...).

⚡ An attribute that's computed

Write:

class Menu:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    @property
    def label(self):
        return f"{self.name} ({self.price})"

coffee = Menu("coffee with milk", 15)
print(coffee.label)     # coffee with milk (15)
Guess first: what does coffee.label(), with brackets, give?

An error: TypeError: 'str' object is not callable. Because of @property, coffee.label is already text, and text can't be called.

Meaning: @property lets you read a method like an attribute, without brackets. Its value is computed again on every read, so it always follows the latest price.

⚡ A setter that guards the value

Write:

class Menu:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("price cannot be negative")
        self._price = value
Guess first: does Menu("iced coffee", -3) become an object?

No. self.price = price in __init__ goes through the setter too (the method under @price.setter), and that setter refuses a negative number. So you get ValueError: price cannot be negative right away.

Meaning: @price.setter runs every time coffee.price = ... is written. The price number itself is kept in self._price, because the name price is already used by the property.

⚡ Static methods and class methods

Meaning: @staticmethod receives neither self (the object) nor cls (the class). It's an ordinary function kept in the class, like Menu.discount(89). @classmethod receives cls, the class itself, for example to make an object from text: Menu.from_text("toast,12").

What you will learn