@property details
- Python course
- Intermediate
- Lesson 38/116
- 5 min
Learn @property in detail.
@property in depth
@property turns a method into a readable attribute. Writing obj.value runs the method behind the scenes; no parentheses needed. This keeps access under control.
Next to it, @value.setter lets you intercept assignment. Example: @temperature.setter\ndef temperature(self, v):\n if v < -273: raise ValueError(...). This blocks negative bounds. With @value.deleter you can also customize the del call. Together the three provide full protection.
The three together
To fully control an attribute you write all three methods. @property intercepts reads, @name.setter writes, @name.deleter deletion. All three share the same name.
Example: on an Account class you write these three for balance; you block negative assignments, log deletion and return the value on read. The attribute name must match all three method names; Python merges them into a single property object.
Practice Write a property for balance
Define a class named Account. Start with def __init__(self, balance):, body self._balance = balance. Add a method def balance(self): with @property, returning self._balance. Add def balance(self, value): with @balance.setter, body self._balance = value. After the class create a = Account(100), assign a.balance = 250 and print with print(a.balance).
Starter code
# Write the Account class with @property and setterSample solution
# Write the Account class with @property and setter
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 = 250
print(a.balance)Expected output
250
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does @x.setter run?
- When you write obj.x = value Correct answer
- When the class is defined
- When you write del obj.x
- When obj.x is read
Explanation: @x.setter runs when a value is assigned to the attribute.
2 Complete the setter line
@property
def balance(self):
return self._balance
____
def balance(self, value):
self._balance = value
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
self._balance = value
Explanation: The @name.setter form binds the setter method.
3 Match the property parts
| Term | Meaning |
|---|---|
@property |
Reads intercepted |
@name.setter |
Writes intercepted |
@name.deleter |
Deletion intercepted |
self._balance |
Hidden attribute |