Python 3 reference · Built-in Functions

Python property() Function

Turn methods into a managed attribute with a getter, and optional setter and deleter. Usually written as @property.

Python 3 Since 3.0

Syntax

@property
def name(self): ...

@name.setter
def name(self, value): ...

Parameters

ParameterDescription
fget, fset, fdel optional Getter, setter and deleter functions.
doc optional The docstring.

Return value

A property descriptor.

Examples

A computed attributeTry it yourself
class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):
        return round(3.14159 * self.radius ** 2, 2)

c = Circle(2)
print(c.area)  # no parentheses: it reads like an attribute

Output

12.57
Validate on assignmentTry it yourself
class Temperature:
    def __init__(self):
        self._celsius = 0

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._celsius = value

t = Temperature()
t.celsius = 21
print(t.celsius)
try:
    t.celsius = -300
except ValueError as e:
    print("ValueError:", e)

Output

21
ValueError: below absolute zero

Good to know

Start with plain attributes. Python lets you switch to a property later without changing the code that uses the attribute, so there's no need for get_x() / set_x() methods.

Version history

VersionChange
Python 3.0Added