Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

property()

Exposes a method as a managed attribute read on an instance.

Version: Python 3.14; repository image, production runtime not attested

Syntax

property(fget=None, fset=None, fdel=None, doc=None)
@property

Exposes a method as a managed attribute read on an instance.

A property without a setter rejects assignment even when the instance has an ordinary attribute dictionary.

On an instance, reading area calls its getter with self and yields 3 × 4 = 12. A property is a data descriptor, so ordinary instance dictionary entries cannot override it. With no setter, assigning 8 raises AttributeError. The setter and deleter decorators can add the corresponding operations.

class Box:
    @property
    def area(self): return 12
b = Box()
b.__dict__["area"] = 8
assert b.area == 12

property.setter

@level.setter calls property.setter to produce a new property with a setter. Reusing the name level keeps the getter and setter on the same exposed descriptor. Assigning m.level=7 updates _level, and rejecting -1 leaves 7.

class Meter:
    def __init__(self):
        self._level = 0
    @property
    def level(self):
        return self._level
    @level.setter
    def level(self, value):
        if value < 0:
            raise ValueError("negative")
        self._level = value
m=Meter()
m.level=7
assert m.level==7
try: m.level=-1
except ValueError: pass
else: raise AssertionError
assert m.level==7

Examples

class Box:
    @property
    def area(self):
        return 3 * 4

box = Box()
print(box.area)
try:
    box.area = 8
except AttributeError as error:
    print(type(error).__name__)

Result

12
AttributeError

On an instance, reading area calls its getter with self and yields 3 × 4 = 12. A property is a data descriptor, so ordinary instance dictionary entries cannot override it. With no setter, assigning 8 raises AttributeError. The setter and deleter decorators can add the corresponding operations.

Sources