In Python, a property getter retrieves a value, while a property setter controls what happens when a value is assigned. Use a setter when assignment needs checking, such as restricting a task’s status to allowed values. section 8.3.4
Listing 8.9 Creating a setter for a property
class Task:
# __init__ stays the same
@property
def status(self):
return self._status
@status.setter
def status(self, value):
allowed_values = ["created", "started", "completed", "suspended"]
if value in allowed_values:
self._status = value
print(f"task status set to {value}")
else:
print(f"invalid status: {value}") #1
The Task example pairs a status getter with a setter that accepts four values and prints a message for an invalid value. section 8.3.4
Use accessor methods selectively:
- Define a setter with @property_name.setter and check the assigned value before updating the internal attribute. section 8.3.4
- Prefer direct attribute access and assignment unless a property is needed for read-only behavior or data verification; routine getters and setters add complexity. section 8.3.4 section 8.3.5












