By WebNest Studio Engineering Team
Python Tutorial
Properties and Descriptors
In Python you start with plain public attributes. If you later need validation, a computed value or a read-only field, you do not have to change every caller from obj.price to obj.get_price() — you turn the attribute into a property. Properties are built on a more general mechanism, descriptors, which also power methods, classmethod, staticmethod and ORM fields.
This lesson covers @property with setters and deleters, computed and cached properties, and writing reusable descriptors with __get__, __set__ and __set_name__.
Why it matters
A property lets a class start with a plain attribute and add validation or a calculation later, without changing any code that uses it. This is why Python code does not need the getter and setter methods that are standard in Java. Descriptors, the mechanism underneath, are how ORMs such as Django and SQLAlchemy make a class attribute behave like a database column.
@property, Setters and Deleters
Decorating a method with @property makes it accessible like an attribute. Add @name.setter to validate or transform assigned values and @name.deleter for deletion. A property without a setter is read-only. Store the real value in a "private" attribute such as self._price.
Computed and Cached Properties
Properties can compute values on the fly — full_name from first and last name, area from width and height — so derived data never goes stale. For expensive computations on objects that do not change, functools.cached_property computes the value once and stores it on the instance.
Descriptors
A descriptor is an object stored as a class attribute that defines __get__ (and optionally __set__, __delete__). Python calls these when the attribute is accessed on instances. __set_name__ tells the descriptor which attribute name it was assigned to. Descriptors let you write validation once — "positive number", "non-empty string" — and reuse it across many classes and fields; this is how Django and SQLAlchemy model fields work.
Examples
Validated attributes and computed properties
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def width(self):
return self._width
@width.setter
def width(self, value):
if value <= 0:
raise ValueError("width must be positive")
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
if value <= 0:
raise ValueError("height must be positive")
self._height = value
@property
def area(self): # computed, read-only
return self.width * self.height
r = Rectangle(3, 4)
print(r.area)
r.width = 10
print(r.area)
try:
r.height = -1
except ValueError as e:
print("ValueError:", e)
try:
r.area = 5
except AttributeError as e:
print("AttributeError:", e)
12
40
ValueError: height must be positive
AttributeError: property 'area' of 'Rectangle' object has no setter
Deleters and cached_property
from functools import cached_property
class User:
def __init__(self, first, last):
self.first, self.last = first, last
self._email = None
@property
def full_name(self):
return f"{self.first} {self.last}"
@property
def email(self):
return self._email or "not set"
@email.setter
def email(self, value):
self._email = value.strip().lower()
@email.deleter
def email(self):
self._email = None
class Report:
def __init__(self, rows):
self.rows = rows
@cached_property
def total(self):
print("computing total...")
return sum(self.rows)
u = User("Asha", "Rao")
u.email = " Asha@Webnest.IN "
print(u.full_name, u.email)
del u.email
print(u.email)
rep = Report([10, 20, 30])
print(rep.total, rep.total)
Asha Rao asha@webnest.in
not set
computing total...
60 60
A reusable validating descriptor
class Positive:
def __set_name__(self, owner, name):
self.private_name = "_" + name
self.public_name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
if not isinstance(value, (int, float)) or value <= 0:
raise ValueError(f"{self.public_name} must be a positive number, got {value!r}")
setattr(obj, self.private_name, value)
class Product:
price = Positive()
stock = Positive()
def __init__(self, name, price, stock):
self.name, self.price, self.stock = name, price, stock
p = Product("Pen", 10, 100)
print(p.price, p.stock, vars(p))
for field, value in [("price", -5), ("stock", "many")]:
try:
setattr(p, field, value)
except ValueError as e:
print("ValueError:", e)
10 100 {'name': 'Pen', '_price': 10, '_stock': 100}
ValueError: price must be a positive number, got -5
ValueError: stock must be a positive number, got 'many'
Common Mistakes
- Storing the value under the same name as the property (self.width inside the width setter), causing infinite recursion.
- Writing get_x/set_x methods everywhere instead of starting with plain attributes and switching to properties later.
- Using cached_property on objects whose inputs change, leaving a stale cached value.
- Putting slow work or side effects in properties that callers assume are cheap.
Exercise
Write a Product class whose price is a property that rejects negative values with a ValueError, and which has a computed read-only property price_with_tax that adds 18%.
Expected output: 118.0 then price cannot be negative
class Product:
def __init__(self, price):
self.price = price
# TODO: property price, with a setter that raises
# ValueError("price cannot be negative") for values below 0
# TODO: read-only property price_with_tax (price plus 18%, rounded to 2 decimals)
product = Product(100)
print(product.price_with_tax)
try:
product.price = -5
except ValueError as error:
print(error)
Show hints
- Store the value in
self._price. The getter is decorated with@propertyand the setter with@price.setter. - Because
__init__assignsself.price, the setter also validates the value given to the constructor.
Show solution
class Product:
def __init__(self, price):
self.price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("price cannot be negative")
self._price = value
@property
def price_with_tax(self):
return round(self._price * 1.18, 2)
product = Product(100)
print(product.price_with_tax)
try:
product.price = -5
except ValueError as error:
print(error)
Quick quiz
1. How is a property named area read?
- A. obj.area()
- B. area(obj)
- C. obj.get_area()
- D. obj.area
Show answer
D. A property is used like an attribute, without parentheses.
2. Which decorator defines the setter for a property named price?
- A. @price.setter
- B. @setter
- C. @property.setter
- D. @set_price
Show answer
A. The setter is attached to the property object created by @property.
3. What does functools.cached_property do?
- A. Recomputes the value on every access
- B. Computes the value on first access and stores it on the object
- C. Makes the attribute private
- D. Shares the value between all objects
Show answer
B. It suits a value that is costly to compute and does not change.
Interview questions
Why use a property instead of getter and setter methods?
Show answer
Code that uses the class keeps the simple attribute syntax, obj.price and obj.price = 10, while the class runs a method behind it. A class can therefore begin with a plain public attribute and switch to a property when validation or a calculation becomes necessary, without any change for its callers. Explicit get_x() and set_x() methods are not idiomatic in Python.
What is a descriptor?
Show answer
A descriptor is an object that defines __get__, __set__ or __delete__ and is assigned as a class attribute. When that attribute is read or written on an instance, Python calls the descriptor's method. Properties, methods, classmethod and staticmethod are all implemented as descriptors, and writing your own lets the same validation be reused for many attributes.
Key Points to Remember
- @property turns methods into attribute-style access; add .setter and .deleter as needed.
- Properties allow validation, read-only fields and computed values without changing callers.
- cached_property computes once per instance.
- Descriptors (__get__, __set__, __set_name__) make reusable attribute logic.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering