CodeBlanks Logo Icon CodeBlanks

@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.

Practice 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.

Starter code

main.py
# Write the Thermometer class
# add a celsius property
# print the value

Sample solution

main.py
# 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)

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does @property return?

main.py
@property
def x(self):
    return self._x
  • A property object Correct answer
  • The attribute value
  • A function object
  • A class

Explanation: answer: a property object. @property returns a property object wrapping the function.

2 Complete the @property definition

Question
class C:
    @____
    def x(self):
        return self._x
Answer
class C:
    @property
    def x(self):
        return self._x

Explanation: @property marks the read method.

3 Match property concepts

Term Meaning
@property Binds read
@x.setter Binds write
property Data descriptor
@x.deleter Binds delete

All lessons in Expert