@x.setter
- Python course
- Intermediate
- Lesson 20/116
- 5 min
Learn setters with @x.setter.
The @balance.setter decorator
The @balance.setter decorator defines the method that runs when a value is assigned to a property. This lets you validate during assignment.
Example: @balance.setter\n def balance(self, value):\n self._balance = value. The assignment a.balance = 200 calls the setter. Inside the setter you can raise an error if value is negative; this keeps the inner data safe.
Validation with a setter
A setter can check the assigned value and reject bad ones. Raising an error or silently returning for invalid values like a negative balance is a common pattern.
Example: def balance(self, value):\n if value < 0:\n return\n self._balance = value. This setter rejects negative values. So a.balance = -50 leaves _balance unchanged; the inner data is protected. Encapsulation works like a gate that guards the inside.
Practice Add a setter to Account
Define the Account class. Add __init__(self, balance) with self._balance = balance. Add @property with def balance(self): and return self._balance. Add @balance.setter with def balance(self, value): and in the body write self._balance = value. Then call a = Account(100), a.balance = 200 and print(a.balance).
Starter code
# Add a setter to the Account classSample solution
# Add a setter to the Account class
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
self._balance = value
a = Account(100)
a.balance = 200
print(a.balance)Expected output
200
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match getter and setter
| Term | Meaning |
|---|---|
@property |
Read |
@balance.setter |
Write |
a.balance = 200 |
Setter runs |
2 When does @x.setter run?
- When the class is defined
- When a method is called
- When the instance is deleted
- On an x = value assignment Correct answer
Explanation: @x.setter runs when a value is assigned to x.
3 Complete the setter body
@balance.setter
def balance(self, value):
self._balance = ____
@balance.setter
def balance(self, value):
self._balance = value
Explanation: The value parameter is assigned to _balance.