1.@property
@property turns a method into something read like a plain attribute — obj.value instead of obj.value(). The method still runs every time the attribute is read, so it can compute, validate, or look something up on the fly.
Key features
- @property goes directly above a method that takes only self
- Callers read it as obj.name, with no parentheses — it looks like a plain attribute
- The method runs fresh on every read — nothing is cached automatically
- Converting a plain attribute to a property later does not break existing callers
- A property with no setter is read-only — assigning to it raises AttributeError
Plain attribute vs. @property, from the caller's side
- obj.area — no parentheses, looks like an attribute
- @property method runs — computes the value fresh, every read
- returns a plain value — caller never sees the method call
Command
class Name:
@property
def value(self):
return self._value # computed, validated, or looked up@property makes a method readable as obj.name, no parentheses — it reruns on every read and is read-only unless a setter is added.