the full guide

Properties

A property lets a method behave like an attribute. With @property you can read a computed value as obj.area, with no brackets, and with @x.setter you can check a value when it's assigned.

6 min Intermediate

What you need: The earlier topics of this module.

Definition

A property lets a method behave like an attribute. With @property you can read a computed value as obj.area, with no brackets, and with @x.setter you can check a value when it's assigned.

In simple words

It looks like reading a plain value, but a small guard runs behind the scenes. Try to set an age of −5 and the guard refuses.

Why it matters

You can begin with a plain attribute and add validation later, without changing any code that uses it. That's why Python rarely needs getX and setX methods.

How it works

In code

properties.py
class Circle:
    def __init__(self, radius):
        self.radius = radius           # goes through the setter below

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("Radius can't be negative")
        self._radius = value

    @property
    def area(self):                    # computed, with no brackets to read it
        return round(3.14159 * self._radius ** 2, 2)

c = Circle(2)
print(c.area)
c.radius = 3
print(c.area)
try:
    c.radius = -1
except ValueError as error:
    print("Refused:", error)

Output

12.57
28.27
Refused: Radius can't be negative

Common mistakes

  • Using the same name inside the setter: self.radius = value calls itself forever. Store it in self._radius.
  • Writing c.area() on a property. It isn't called with brackets.

Check yourself

Question 1

1. How do you read a property named area?

Question 2

2. What is a setter useful for?

Summary

  • @property makes a method read like an attribute.
  • Setters validate values on assignment.

Finished reading?

Sources: The Python Tutorial, python.org