ZetCode

Python property decorator

last modified November 30, 2026 Python 3.15

In this article we show how to use the @property decorator in Python.

A property is an attribute whose reading, assignment, and deletion are handled by methods. Code that uses the object writes obj.radius or obj.radius = 3 as with a plain attribute, while the class runs a method that can validate the value, compute it from other data, or refuse the change. Properties let a class start with plain attributes and add such rules later without changing the code that uses it.

The article assumes knowledge of Python methods and Python decorators.

A plain attribute

We start with a class that stores its data in an ordinary attribute. Any code can assign any value to it.

plain_attribute.py
class Circle:

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2


c = Circle(2)
print(c.radius, c.area())

c.radius = -5
print(c.radius, c.area())

The Circle class keeps the radius in the radius attribute. Nothing stops us from assigning a negative number, and the area method then happily computes an area for a circle that cannot exist. The rest of this article adds control over the attribute without changing how it is used.

$ python plain_attribute.py
2 12.56636
-5 78.53975

A read-only property

The @property decorator turns a method into a getter. The method is called when the attribute is read, without parentheses.

read_only.py
class Circle:

    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius


c = Circle(2)
print(c.radius)

try:
    c.radius = -5
except AttributeError as e:
    print(e)

print(c.radius)

The value is stored in _radius; the leading underscore marks it as internal by convention. The radius method is decorated with @property, so c.radius calls it and returns the stored value. The property has no setter, so an assignment raises an AttributeError and the radius stays unchanged.

$ python read_only.py
2
property 'radius' of 'Circle' object has no setter
2

Adding a setter

A setter is a second method with the same name, decorated with @radius.setter. It runs on every assignment and can check the new value.

setter.py
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(f"radius must not be negative, got {value}")
        self._radius = value


c = Circle(2)
c.radius = 3.5
print(c.radius)

try:
    c.radius = -5
except ValueError as e:
    print(e)

try:
    Circle(-1)
except ValueError as e:
    print(e)

print(c.radius)

The @property line creates a property object named radius, and @radius.setter creates a copy of it with the setter added. Both methods must therefore have the same name. The constructor assigns self.radius rather than self._radius, so the validation applies to new objects as well. An invalid value raises a ValueError and leaves the old value in place.

$ python setter.py
3.5
radius must not be negative, got -5
radius must not be negative, got -1
3.5

Computed properties

A property does not need its own stored value. It can compute the result from other attributes each time it is read.

computed.py
class Temperature:

    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def fahrenheit(self):
        return self.celsius * 9 / 5 + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        self.celsius = (value - 32) * 5 / 9

    @property
    def kelvin(self):
        return self.celsius + 273.15


t = Temperature(25)
print(t.celsius, t.fahrenheit, t.kelvin)

t.celsius = 100
print(t.celsius, t.fahrenheit, t.kelvin)

t.fahrenheit = 32
print(t.celsius, t.fahrenheit, t.kelvin)

Only the temperature in Celsius is stored. The fahrenheit and kelvin properties are computed from it, so they always agree with the current value. The fahrenheit property also has a setter that converts the value back and stores it in celsius; kelvin has no setter and is read-only.

$ python computed.py
25 77.0 298.15
100 212.0 373.15
0.0 32.0 273.15

A deleter

The @name.deleter decorator defines a method that runs on del obj.name. It is the least used of the three, but it is handy when deleting should restore a default.

deleter.py
class Player:

    def __init__(self, login):
        self.login = login
        self._nickname = None

    @property
    def nickname(self):
        if self._nickname is None:
            return self.login
        return self._nickname

    @nickname.setter
    def nickname(self, value):
        self._nickname = value.strip()

    @nickname.deleter
    def nickname(self):
        print(f"removing nickname of {self.login}")
        self._nickname = None


p = Player("jmartin")
print(p.nickname)

p.nickname = "  Falcon "
print(p.nickname)

del p.nickname
print(p.nickname)

A player's nickname falls back to the login when none is set. The setter strips surrounding spaces, and the deleter resets the stored value to None, which brings back the default. Without a deleter, del p.nickname would raise an AttributeError.

$ python deleter.py
jmartin
Falcon
removing nickname of jmartin
jmartin

Caching with cached_property

A property runs its method on every access. For an expensive value that does not change, functools.cached_property computes the value once and stores it in the instance.

cached.py
import functools


class Report:

    def __init__(self, values):
        self.values = values

    @property
    def total(self):
        print("computing total")
        return sum(self.values)

    @functools.cached_property
    def stats(self):
        print("computing stats")
        n = len(self.values)
        mean = sum(self.values) / n
        return n, mean, min(self.values), max(self.values)


r = Report([4, 8, 15, 16, 23, 42])

print(r.total)
print(r.total)

print(r.stats)
print(r.stats)

r.values.append(100)
print(r.stats)

del r.stats
print(r.stats)

The total property is computed twice for two reads. The stats attribute is computed on the first read only; the result is saved in the object, and later reads return the saved tuple. The cache is not refreshed automatically: after a value is appended, stats still shows the old numbers. Deleting the attribute removes the cached value, so the next read computes it again.

$ python cached.py
computing total
108
computing total
108
computing stats
(6, 18.0, 4, 42)
(6, 18.0, 4, 42)
(6, 18.0, 4, 42)
computing stats
(7, 29.714285714285715, 4, 100)

The property function

property is a built-in class. The decorator form is a shortcut for calling it with the getter, setter, and deleter functions.

property_function.py
class Account:

    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def get_balance(self):
        return self._balance

    def set_balance(self, value):
        if value < 0:
            raise ValueError("balance must not be negative")
        self._balance = round(value, 2)

    balance = property(get_balance, set_balance,
                       doc="Account balance, rounded to cents.")


acc = Account("Lucia", 120.456)
print(acc.balance)

prop = Account.balance
print(type(prop).__name__)
print(prop.__doc__)
print(prop.fget(acc))
print(prop.fset is Account.set_balance, prop.fdel)

Here the getter and setter are ordinary methods, and the class attribute balance is created by calling property with them and a docstring. Reading Account.balance on the class returns the property object itself. Its fget and fset attributes hold the two functions, and fdel is None because no deleter was given. The getter and setter also remain available as regular methods, which the decorator form avoids. Properties are implemented with descriptors, which are explained in Python __get__ method.

$ python property_function.py
120.46
property
Account balance, rounded to cents.
120.46
True None

Properties in subclasses

A subclass can change one part of an inherited property. Redefining the property with @property would replace the whole property, setter included.

inheritance.py
class Product:

    def __init__(self, name, price):
        self.name = name
        self.price = price

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("price must not be negative")
        self._price = value


class SaleProduct(Product):

    @Product.price.getter
    def price(self):
        return round(self._price * 0.8, 2)


class BrokenSale(Product):

    @property
    def price(self):
        return round(self._price * 0.8, 2)


p = SaleProduct("lamp", 45.0)
print(p.name, p.price)

p.price = 60
print(p.name, p.price)

try:
    BrokenSale("chair", 80.0)
except AttributeError as e:
    print(e)

SaleProduct uses @Product.price.getter, which copies the parent property with a new getter and keeps the validating setter. The sale price is 80 percent of the stored price, and assignment still works. BrokenSale defines a new property with only a getter, so the constructor's self.price = price fails: the subclass property has no setter.

$ python inheritance.py
lamp 36.0
lamp 48.0
property 'price' of 'BrokenSale' object has no setter

Source

property, functools.cached_property, Descriptor guide: properties

In this article we have turned methods into attributes with the @property decorator, added setters with validation and a deleter, computed values on access, cached them with cached_property, used the property function directly, and changed a property in a subclass. Use a property when an attribute needs a rule; a plain attribute is enough when it does not. See also Python static methods, Python abstract classes, and Python dataclass.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.