What problem does the `@property` decorator solve, and how does it let you add validation without breaking existing attribute-style access?
Answer
`@property` turns a method into something accessed like a plain attribute (`obj.value` instead of `obj.value()`), which lets a class start with simple public attributes and later add computed behavior, validation or logging without forcing every caller to rewrite `obj.value` as `obj.get_value()`. A paired `@value.setter` method can validate or transform an assigned value before storing it internally, so `obj.value = -5` can raise a `ValueError` from inside what still looks like ordinary attribute assignment to the caller.
Strong answer includes
- exposes a method through attribute-style access syntax
- lets you add validation later without breaking the public API
- a matching @x.setter intercepts assignment for validation
Practical example
@property
def radius(self): return self._radius
@radius.setter
def radius(self, value):
if value < 0: raise ValueError("radius must be non-negative")
self._radius = valuekeeps
circle.radius = 5working while rejecting
circle.radius = -1.