What does the @property decorator do in Python?
@property turns a method into a read-only attribute, so obj.area calls the method without parentheses. Adding @name.setter lets you validate or compute on assignment while callers still use plain attribute syntax.
Explain it simply
At a bank counter you say "my balance", and the clerk checks the ledger for you. You use a simple noun, but work happens behind it. A property is that: attribute-style access hiding a method call, where you can add checks later without changing how anyone uses the class.
Example
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("radius cannot be negative")
self._radius = value
@property
def diameter(self):
return self._radius * 2
c = Circle(5)
print(c.diameter) # Output: 10
c.radius = 7
print(c.diameter) # Output: 14
try:
c.radius = -1
except ValueError as e:
print(e) # Output: radius cannot be negative
try:
c.diameter = 3
except AttributeError:
print("read-only") # Output: read-onlyWhat to say in the interview
"A property lets a method behave like an attribute. With a setter it can validate input, and without one it is read-only. It lets me start with a plain attribute and add validation later without breaking callers, so Python code doesn't need Java-style getters and setters."
Common mistakes
- Using the same name for the attribute and the property, such as
self.radius = ...inside the setter, which recurses forever. Store it inself._radius.