Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Object-oriented PythonMiddleCommonPractical

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

Python 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 = value

keeps

Python example
circle.radius = 5

working while rejecting

Python example
circle.radius = -1

.

#property#encapsulation#oop

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocolsThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics