bhylu.com

Advertisements

Class Properties

A property exposes method-controlled access through attribute syntax. It is useful when a value needs validation or is derived from other state.

Understand the idea

The property decorator defines a getter. A setter can validate a replacement before storing it in a separate backing attribute. Keep attribute access reasonably unsurprising: expensive network work or hidden writes in a simple getter can confuse callers. A leading underscore communicates an internal implementation detail rather than enforced secrecy.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Stock:
    def __init__(self, count):
        self.count = count
    @property
    def count(self):
        return self._count
    @count.setter
    def count(self, value):
        if value < 0:
            raise ValueError("Negative stock")
        self._count = value

print(Stock(8).count)

Read the result

The property reads as an ordinary attribute and returns 8. Its setter rejects a negative replacement.

Try one change

Assign a new valid count and a negative count, and confirm that rejected input does not replace the valid stored value.