@property
@property turns a method into something callers read like a plain attribute. It lets you add validation or computation behind order.qty later, without changing a single line of code that already uses it.
Detailed Explanation
If you learned OOP in Java or C++, you were taught to make every field private and write getQty() and setQty() on day one, even when they do nothing. The reason is not style. In Java, order.qty and order.getQty() are different syntax, so promoting a public field to a method later breaks every caller. Defensive accessors are insurance against a change you might never make.
Python has no such trap. Attribute access is a hook the class controls, so order.qty can be a stored value today and a computed value tomorrow with no change at the call site. That is why idiomatic Python starts with a plain public attribute and reaches for @property only when a real rule appears.
A property has up to three parts. @property on a method defines the getter, which runs when someone reads the attribute. @qty.setter defines what happens on assignment. @qty.deleter defines what happens on del. You define the setter and deleter by decorating a second and third function with the same name as the getter, which is why the property name appears in the decorator.
The property object lives on the class. The actual data lives on the instance, conventionally in an attribute with a leading underscore such as self._qty. Confusing the two produces the most common property bug: if the getter for qty returns self.qty, it calls itself and you get a RecursionError.
Leaving out the setter is a feature, not an oversight. A getter-only property is read-only, which is the natural shape for a derived value. If a line's total is always qty * unit_price, expose it as a read-only property instead of storing it. There is then no way for total to drift out of sync with the fields it depends on, because it is recomputed on every read.
That recomputation is the cost. A property read is a Python function call, several times slower than fetching a value out of the instance dictionary. It rarely matters, but inside a tight numeric loop it does, and the fix is to read the value into a local variable once.
Two rules worth holding onto. First, if a property has a getter and a setter that do nothing but move a value in and out of self._x, delete the property and expose x as a public attribute; the property is pure noise. Second, properties are not access control — _qty is still reachable and Python will not stop anyone touching it.
Under the hood a property is an instance of the built-in property class, which is a descriptor. That is the general mechanism; @property is the convenient special case.
Code Examples
class Thermostat:
def __init__(self, celsius: float):
self._celsius = celsius # backing store, note the underscore
@property
def celsius(self) -> float: # runs on READ of .celsius
return self._celsius
@celsius.setter # decorator name must match the getter
def celsius(self, value: float) -> None: # runs on ASSIGNMENT to .celsius
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
@property
def fahrenheit(self) -> float: # no setter -> read-only, always derived
return self._celsius * 9 / 5 + 32
t = Thermostat(21.0)
print(t.celsius) # 21.0 <- looks like a field, runs a method
print(t.fahrenheit) # 69.8
t.celsius = 23.5 # goes through the setter, so the check runs
print(t.fahrenheit) # 74.3
try:
t.celsius = -300
except ValueError as exc:
print(exc) # below absolute zero
try:
t.fahrenheit = 100 # no setter was defined for fahrenheit
except AttributeError as exc:
print(exc) # property 'fahrenheit' of 'Thermostat' object has no setter# Start plain. Add the property only when a rule shows up.
class CartLine:
def __init__(self, sku: str, qty: int):
self.sku = sku # public attribute, no ceremony needed
self.qty = qty
# Weeks later, the business says qty must be at least 1.
# Callers keep writing `line.qty = 3`. Nothing outside this class changes.
class CartLine:
def __init__(self, sku: str, qty: int):
self.sku = sku
self.qty = qty # goes through the setter below
@property
def qty(self) -> int:
return self._qty # read the BACKING attribute, never self.qty
@qty.setter
def qty(self, value: int) -> None:
if value < 1:
raise ValueError("qty must be at least 1")
self._qty = value
line = CartLine("A1", 3)
print(line.qty) # 3
try:
line.qty = 0
except ValueError as exc:
print(exc) # qty must be at least 1Common Gotchas
Infinite recursion from the wrong backing name
a getter for `qty` that returns `self.qty` calls itself forever and dies with `RecursionError`. The getter must read a differently named attribute, conventionally `self._qty`.
Overriding a property in a subclass discards the parts you did not redefine
if the parent has a getter and a setter for `x` and the child redefines only `@property def x`, the child's `x` becomes read-only. Redefine the setter too, or call the parent property explicitly.
Properties only work on new-style classes and only when defined on the class
assigning a `property` object to an instance (`obj.x = property(...)`) stores an ordinary object in the instance dictionary and does nothing special, because Python looks up descriptors on the type.
A property is not privacy
`_celsius` is a naming convention. Anyone can read or write it and bypass every check. Use properties for computed values and invariants, not to keep other programmers out.