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:
@propertyfor an attribute that is computed or guarded,@staticmethodfor a helper function that needs no object,@classmethodfor a method that works with the class, not with one object.
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)
@propertylets you read the methodlabellike an attribute:coffee.label, without brackets. Python calls the method for you.- The value of
coffee.labelis computed again every time it is read, so it always follows the latest price: aftercoffee.price = 17, the label changes too. An attribute whose value is computed when it is read is called a computed attribute. coffee.label()with brackets is an error.coffee.labelis already text, and text cannot be called:TypeError: 'str' object is not callable.- A property with no setter can only be read (the next section explains setters).
coffee.label = "cheap"is refused:AttributeError: property 'label' of 'Menu' object has no setter.
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
@property def priceis the getter: it runs whencoffee.priceis read.@price.setterabovedef price(self, value)is the setter: it runs whencoffee.price = ...is written.valueholds the number on the right of the=. The setter method must have the same name as its getter,price.raise ValueError("...")stops the program with an error you choose. The try/except lesson, later, shows how to handle an error like this.- The price number itself is kept in another attribute,
self._price, because the namepriceis already used by the property. An underscore in front of a name is a convention (an agreement between developers) that means "do not touch this from outside the class". Python does not forbid it, but every developer knows what it means. self.price = pricein__init__goes through the setter too. SoMenu("iced coffee", -3)is refused at the moment it is made, withValueError: price cannot be negative. The object is never made.
@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
@staticmethodreceives neitherselfnorcls(the class, see the next item). It is an ordinary function kept inside the class because it is related to the class.discountfrom the if/elif lesson only needs a total. It does not need the data of any menu item.@classmethodreceivescls, the class itself, as its first parameter. Insidefrom_text,text.split(",")cuts the text at the comma into a name and a price, thenint(price)turns the price from text into a number.cls(name, int(price))is the same asMenu(name, int(price)). This pattern is called an alternative constructor: another way to make an object. Here the object is made from the text"toast,12", without changing__init__.- Why
clsand notMenudirectly? When the method is called from a child class, for exampleDrinkMenu.from_text("iced tea,7"),clsholdsDrinkMenu. So the object that is made belongs to the child class. - A static method and a class method can both be called through the class name, without making an object first. Calling through an object works too:
toast.discount(120)gives 15.
⚠️ Too many brackets, and a setter that calls itself
- Calling a property with brackets.
coffee.label()fails:TypeError: 'str' object is not callable. A property is read without brackets. - A setter that stores into its own name.
self.price = valueinside thepricesetter calls that setter again, again and again, until you getRecursionError: maximum recursion depth exceeded. Store it inself._price. - A setter named differently from its property.
@price.setterabovedef change_price(...)does not attach a setter toprice. Soself.price = pricein__init__is refused:AttributeError: property 'price' of 'Menu' object has no setter. - Forgetting
@staticmethod.def discount(total):with no decorator, thencoffee.discount(89): Python also sendscoffee, so you getTypeError: Menu.discount() takes 1 positional argument but 2 were given.
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").