Lesson 7 of 15 · Behaviour
Properties
Learn how Python properties let you run code when an attribute is read or changed: computed values, getters, setters with validation and read-only attributes.
- 8 min read
- Intermediate
- Reviewed
- What a property is and why it is useful
- How to make an attribute that is worked out when you read it
- How a setter can check a new value before it is saved
- How to make an attribute read-only
The problem: plain attributes accept anything
With plain attributes, anyone can store anything, even nonsense:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
ada = Person("Ada", 36)
ada.age = -200 # Python happily accepts this
print(ada.age)__init__ can check the age when the object is created, but nothing checks it later. You could write a set_age() method, but then everyone has to remember to use it, and ada.age = ... would still bypass it. Properties solve this neatly.
What is a property?
You create one with the @property decorator.
Computed attributes
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
box = Rectangle(4, 3)
print(box.area)
box.width = 10
print(box.area)Two things to notice:
- You read it as
box.area, with no brackets, just like a normal attribute. - It is always up to date. After the width changed, the area changed with it, because it is worked out fresh every time.
If area were stored in __init__ instead, it would still say 12 after the width changed. A property can never go out of date.
Getters and setters
Here is the Person class again, now protecting the age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age # this line already uses the setter below
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value
ada = Person("Ada", 36)
print(ada.age)
ada.age = 37
print(ada.age)
try:
ada.age = -200
except ValueError as error:
print("Refused:", error)
print(ada.age)Here is what happens:
ada.ageruns the getter, which returns the stored value.ada.age = 37runs the setter, which checks the value and stores it.ada.age = -200also runs the setter, which refuses it. The old age is kept.
Even self.age = age inside __init__ goes through the setter, so the check runs when the object is created too. One rule, in one place, always enforced.
Why self._age with an underscore?
The property is called age, so the real value needs a different name to be stored under. By convention, programmers add a leading underscore: self._age. The underscore says "this is internal, please use age instead". You will learn more about this in the Encapsulation lesson.
Read-only properties
class Order:
def __init__(self, order_id, prices):
self._order_id = order_id
self.prices = prices
@property
def order_id(self):
return self._order_id
@property
def total(self):
return sum(self.prices)
order = Order("A-1001", [250, 120])
print(order.order_id, order.total)
try:
order.order_id = "HACKED"
except AttributeError:
print("The order ID cannot be changed")An order number should never change after the order exists, so leaving out the setter is the right design.
Properties that convert values
A property can also present the same data in a different form:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@property
def fahrenheit(self):
return self.celsius * 9 / 5 + 32
@fahrenheit.setter
def fahrenheit(self, value):
self.celsius = (value - 32) * 5 / 9
room = Temperature(20)
print(room.fahrenheit)
room.fahrenheit = 212
print(room.celsius)Only Celsius is stored. Fahrenheit is calculated on the way out and converted on the way in, so the two can never disagree.
Common mistakes
Protect a price with a setter, and add a computed, read-only price with tax.
# Write a class called Product.
# - __init__(self, name, price) stores the name and sets self.price = price
# - price is a property: the getter returns self._price
# and the setter raises ValueError("Price must be positive") if the value is 0 or less
# - price_with_tax is a read-only property that returns price * 1.18, rounded to 2 places
phone = Product("Phone", 10000)
print(phone.price_with_tax)
phone.price = 12000
print(phone.price_with_tax)
try:
phone.price = 0
except ValueError as error:
print(error)
print(phone.price)
# Output must be exactly:
# 11800.0
# 14160.0
# Price must be positive
# 12000
A class has an area property. How do you read it?
Summary
- A property looks like an attribute but runs your code when it is read or changed.
@propertymakes the getter. Use it for computed attributes that are always up to date.@name.settermakes the setter, the perfect place to check new values.- Store the real value under a different name, usually with a leading underscore, like
self._age. - A property with no setter is read-only.
Next: the special methods that let your objects work with print, +, ==, len() and more.
Finished reading? Tick it off to track your progress.