Computed attributes
Expose a computed value without changing the public access syntax.
Python · Decorator
The property decorator exposes method-based behavior through normal attribute syntax. It can provide controlled reading, writing, deletion, and documentation for an attribute.
property creates a managed attribute from optional getter, setter, deleter, and documentation functions. Decorating a method with @property supplies read access; its .setter and .deleter helpers add assignment and deletion behavior while callers use ordinary attribute syntax.
property(fget=None, fset=None, fdel=None, doc=None)| Name | Type | Description |
|---|---|---|
fget | callable | None | Function called to retrieve the attribute value; defaults to None. |
fset | callable | None | Function called to assign an attribute value; defaults to None. |
fdel | callable | None | Function called to delete the attribute value; defaults to None. |
doc | str | None | Documentation string for the attribute; defaults to None. |
A property attribute.
class User:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not value:
raise ValueError("name cannot be empty")
self._name = value
user = User("Ada")
print(user.name)
user.name = "Grace"
print(user.name)The getter exposes name as an attribute, while the setter validates assignments.
Expose a computed value without changing the public access syntax.
Reject invalid assignments before storing state.
Preserve an attribute-like API while changing internal representation.
property is a built-in class that returns a property attribute. Its getter, setter, and deleter functions control reads, writes, and deletes.
Follow-up: How do you add write behavior after using @property? Define a method with the same property name and decorate it with @name.setter.
fget is called when the attribute is read, fset when it is assigned, and fdel when it is deleted. The doc argument supplies the attribute documentation.
Follow-up: What happens if fset is omitted? Assignment through the property raises AttributeError.
The decorator form uses @property on a method to create the getter, then uses the returned property's setter or deleter decorators for optional mutation behavior. The underlying storage is commonly kept under a different instance attribute name.
Follow-up: Why use a separate backing attribute? It prevents the getter or setter from recursively referring to the property itself.
property.setterproperty.deleterproperty.getterAttributeErrordescriptor