Python
@property
Learn that @property is a descriptor.
Is @property a descriptor?
Yes — @property is a data descriptor. The property class implements __get__, __set__ and __delete__ behind the scenes and wires them to your functions.
@property marks the read function. @name.setter wires the write function, @name.deleter the delete function. So you get the full power of the descriptor protocol without writing it by hand. property is the most commonly used descriptor and is more readable than writing a custom one in most cases.
Validation with property
@property and @name.setter together are used for validation. You put an if inside the setter and reject invalid values with raise ValueError.
You store the internal value under a leading underscore like self._x; this is the Python convention for 'private'. The property appears as x from outside but every access goes through the functions. This pattern keeps the external API stable while hiding the internal representation. When the user writes obj.x = -5 the setter validates and raises if needed.
Exercise Temperature validation with property
Write a Thermometer class. In __init__ set self._celsius = 0. Add a celsius read method with @property returning self._celsius. Add a write method with @celsius.setter that raises ValueError if the value is less than -273; otherwise sets self._celsius = value. Create an instance, set celsius = 25 and print it.
Show example solution
# Write the Thermometer class
class Thermometer:
def __init__(self):
self._celsius = 0
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273:
raise ValueError("too low")
self._celsius = value
t = Thermometer()
t.celsius = 25
print(t.celsius)
Test yourself
-
What does @property return?
@property
def x(self):
return self._x
- A property object
- The attribute value
- A function object
- A class
Show answer
A property object — answer: a property object. @property returns a property object wrapping the function.
-
Complete the @property definition
class C:
@____
def x(self):
return self._x
Show answer
class C:
@property
def x(self):
return self._x
-
Match property concepts
- @property
- Binds read
- @x.setter
- Binds write
- property
- Data descriptor
- @x.deleter
- Binds delete
Next lesson: __set_name__