Setters: a guard at the gate
🌍 In real life. An online form won't take an age of -3. The moment you type it, the form checks it and says "that's not a real age", and your old answer stays. Bad data never gets in.
A setter is that check for an attribute. Every time someone writes s.age = …, Python runs your setter method first. It can:
- accept the value and store it, or
- refuse it by raising a
ValueError, so the old value stays
The idea in one sentence: a setter (@name.setter) runs every time someone writes obj.name = value, so it can check or tidy the value before storing it.
Its words:
- setter: the method that runs on assignment
_age: the real stored value; the_says "useageinstead"- validate: check a value and refuse a bad one with a
ValueError
Here's how the pieces fit, step by step:
- the real value lives in
self._age(the_means "private, useageinstead") - the
@propertygetter hands backself._age - the
@age.setterchecks each new value before it's stored - even
__init__writesself.age = age, so the very first value is checked too
Watch the guard at work: good values go through the gate into the vault, a bad one is stopped at the barrier.
class Student:
def __init__(self, age):
self.age = age # goes through the setter
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("age must be 0 or more")
self._age = value
s = Student(15)
s.age = 16
print(s.age)
try:
s.age = -3
except ValueError as e:
print("Refused:", e)
print(s.age) # still 16A setter can also tidy a value before storing it. A sign-up form trims the spaces people type by accident around their name:
class User:
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value.strip().title()
u = User(" ada lovelace ")
print(u.name)Mistakes and edge cases.
- Storing in the property's own name.
self.age = valueinside the age setter calls the setter again, forever; storeself._age = value. - Setting _age directly.
s._age = -3skips the check. The underscore is a polite "don't", not a lock. - A different name for the setter. The setter must be
@age.setterabovedef age(...): the same name as the property. - Not checking in init. Write
self.age = age(notself._age) in__init__, so the very first value is checked too, and a bad one is refused with a ValueError.
Quiz
What does this print?
class Box: def __init__(self, size): self.size = size @property def size(self): return self._size @size.setter def size(self, value): if value < 0: raise ValueError("no") self._size = value b = Box(3) try: b.size = -1 except ValueError: print("refused") print(b.size)Why does
__init__writeself.age = agerather thanself._age = age?- So the first value is checked by the setter too
- Because _age is not allowed in __init__
- It makes no difference
What does this print?
class Tag: def __init__(self, text): self.text = text @property def text(self): return self._text @text.setter def text(self, value): self._text = value.upper() t = Tag("sale") t.text = "new" print(t.text)Which decorator goes on the setter for a property called
price?- @price.setter
- @setter
- @property.setter
Which line has a mistake?
class Box: def __init__(self, size): self.size = size @property def size(self): return self._size @size.setter def size(self, value): self.size = value b = Box(3)
Coding tasks
Make
balancea property ofAccountwhose setter raises aValueErrorfor a negative balance. MakingAccount(-5)must be refused too.Make
namea property ofPlayer. The setter strips spaces from both ends, and raises aValueErrorif nothing is left.