liveBook · Manning

Property decorator

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A Python property decorator defines attribute-like access backed by methods that can compute, validate, or otherwise control attribute values.

A moving rectangle needs readable position updates, but its coordinates must stay within the screen. Ordinary getter and setter methods can control those updates, though calls such as `rectangle.set_x(rectangle.get_x() + 1)` obscure the simple movement. Properties keep `rectangle.x += 1` while putting the control inside the class. section 4.1.2

@property
    def x(self):
        return self._x
 
    @x.setter
    def x(self, value):
        if not (0 < value < SCREEN_WIDTH - self.width):
            self.dir_x = -self.dir_x
        self._x += abs(self._x - value) * self.dir_x

The `@property` method reads `_x`; the `@x.setter` method handles assignments to `x`, reversing horizontal direction when the requested position crosses a screen boundary. section 4.1.2

The underscore in `_x` signals that callers should use the property, not the stored attribute directly; it does not enforce privacy. Use a property when an attribute needs behavior without making callers switch to method-call syntax. section 4.1.2

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Works through a getter and boundary-aware setter, contrasting them with explicit methods; does not develop an exhaustive property reference.
Examples
Uses a moving rectangle, contrasting direct coordinate updates with explicit getter and setter calls.
What it assumes
Assumes familiarity with Python classes, methods, and instance attributes rather than teaching their syntax from zero.
What you can do after
Apply it via Python’s `@property` and `@x.setter` decorators to control coordinate updates without changing callers’ attribute syntax.
How it connects
Connects properties to class attributes, getters and setters, underscore naming conventions, and screen-boundary handling.

Also explained in

Compare how 2 books explain property decorator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.