Interview frequency: …
Short answer
A property exposes a computed or validated value through plain attribute syntax, and you can start with a simple attribute and turn it into a property later without breaking the interface.
Explanation
In Python there is no need to write getX and setX up front as in Java; start with a public attribute and, when you need validation or computation, convert it into a property. A property is a descriptor at its core. Reading it should stay cheap and free of surprising side effects; if it performs I/O or heavy computation, it is clearer as an explicit method, or use functools.cached_property for expensive values that do not change.
Code example
class Account:
def __init__(self, balance: int):
self.balance = balance # Passes through setter
@property
def balance(self) -> int:
return self._balance
@balance.setter
def balance(self, value: int) -> None:
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = valueCommon mistakes
- Running a database query inside a property that is called in loops without noticing.
- Writing getters and setters for every field without need, as in Java.