Python 3D Academyবাংলা

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 "use age instead"
  • validate: check a value and refuse a bad one with a ValueError

Here's how the pieces fit, step by step:

  1. the real value lives in self._age (the _ means "private, use age instead")
  2. the @property getter hands back self._age
  3. the @age.setter checks each new value before it's stored
  4. even __init__ writes self.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 16
The getter and the setter share one name, age. The setter's decorator is @age.setter.

A 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 = value inside the age setter calls the setter again, forever; store self._age = value.
  • Setting _age directly. s._age = -3 skips the check. The underscore is a polite "don't", not a lock.
  • A different name for the setter. The setter must be @age.setter above def age(...): the same name as the property.
  • Not checking in init. Write self.age = age (not self._age) in __init__, so the very first value is checked too, and a bad one is refused with a ValueError.

Quiz

  1. 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)
  2. Why does __init__ write self.age = age rather than self._age = age?

    • So the first value is checked by the setter too
    • Because _age is not allowed in __init__
    • It makes no difference
  3. 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)
  4. Which decorator goes on the setter for a property called price?

    • @price.setter
    • @setter
    • @property.setter
  5. 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

  1. Make balance a property of Account whose setter raises a ValueError for a negative balance. Making Account(-5) must be refused too.

  2. Make name a property of Player. The setter strips spaces from both ends, and raises a ValueError if nothing is left.