Python
@property details
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.
Exercise 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).
Show example 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)
Test yourself
-
When does @x.setter run?
- When you write obj.x = value
- When the class is defined
- When you write del obj.x
- When obj.x is read
Show answer
When you write obj.x = value — @x.setter runs when a value is assigned to the attribute.
-
Complete the setter line
@property
def balance(self):
return self._balance
____
def balance(self, value):
self._balance = value
Show answer
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
self._balance = value
-
Match the property parts
- @property
- Reads intercepted
- @name.setter
- Writes intercepted
- @name.deleter
- Deletion intercepted
- self._balance
- Hidden attribute
Next lesson: @cached_property