Sub topic 7
Controlling attribute access with properties
This chapter assumes you can write a class with __init__ and instance methods, and that you know how self stores per-instance state. If you need a refresher, review the chapters on initializers and instance methods first.
The problem properties solve
Plain attributes are the Python default. You write obj.value = 5 and read obj.value. There are no getter and setter methods. That is fine until you need to check a value, compute it, or change how it is stored without breaking callers.
A property is a descriptor built into Python. It lets you run a method when code reads, assigns, or deletes an attribute, while callers keep using plain attribute syntax. You can start with a simple attribute and add a property later. No calling code has to change.
A validating property
The Temperature class below validates every assignment to celsius and exposes fahrenheit as a computed value.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius # goes through the setter
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("temperature below absolute zero")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
t = Temperature(100)
print(t.fahrenheit) # 212.0
t.celsius = 0
print(t.fahrenheit) # 32.0Three things happen here:
@propertyturns thecelsiusmethod into a getter. Readingt.celsiuscalls it.@celsius.setterattaches a setter to that same property. Assigningt.celsius = 0calls it.fahrenheithas no setter, so it is read-only and computed on each access.
The value is stored in self._celsius. The leading underscore is a convention that means "internal, do not touch directly". Python does not enforce it.
Why `__init__` assigns to `self.celsius`
Look at the first line of __init__. It assigns to self.celsius, not self._celsius. This sends the starting value through the setter, so Temperature(-500) fails right away instead of creating an invalid object.
try:
Temperature(-500)
except ValueError as exc:
print(exc) # temperature below absolute zeroThe data flow
Common errors
The most common mistake is infinite recursion. If the getter or setter uses the public name to store the value, it calls itself.
class Broken:
@property
def size(self):
return self.size # calls the getter again
@size.setter
def size(self, value):
self.size = value # calls the setter againReading or assigning size raises RecursionError. Store the value under a different name, such as _size.
Other errors to watch for:
- Forgetting the setter. Assigning to a property with no setter raises
AttributeError. This is useful for read-only values, but surprising if you did not intend it. - Reusing the wrong decorator name. The setter must be written as
@celsius.setterand the method must have the same name,celsius. A different name creates a separate attribute and leaves the original property read-only. - Hiding expensive work. A property looks like a cheap attribute lookup. If the getter does slow work such as a network call, callers will not expect it. Use a regular method for that, or cache the result.
- Skipping the property in
__init__. If__init__assigns toself._celsiusdirectly, the validation never runs for the initial value.
Properties are not privacy
A property does not hide data. t._celsius = -999 still works and bypasses the check. Python relies on convention here. The underscore signals that the attribute is internal, and the property provides the supported way to use it.
Choosing between a property and a method
| Situation | Use |
|---|---|
| Value is cheap to get and feels like data | Property |
| Value must be validated on assignment | Property with a setter |
| Value is derived from other attributes | Read-only property |
| Operation is slow, has side effects, or takes arguments | Method |
Exercise
A class Account has a property balance with a getter and a setter that rejects negative values. In __init__, a developer writes self._balance = balance. What is wrong, and how do you fix it?
Show answer
Assigning to self._balance bypasses the setter, so a negative starting balance is accepted without validation. Change the line to self.balance = balance so the initial value goes through the setter.
Exercise
What happens if you assign t.fahrenheit = 50 on the Temperature class above, and how would you make that assignment work?
Show answer
It raises AttributeError because fahrenheit has no setter. Add a method decorated with @fahrenheit.setter that converts the value to Celsius, for example self.celsius = (value - 32) * 5 / 9, so the celsius setter still validates it.