Home >Backend Development >Python Tutorial >How Does the `@property` Decorator Function in Python?

How Does the `@property` Decorator Function in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 05:30:10500browse

How Does the `@property` Decorator Function in Python?

How the @property Decorator Works in Python

The @property decorator is a powerful tool for creating read-only or read-write attributes on Python classes. It simplifies the creation of properties by wrapping them in a decorator function.

How the Built-in Property Decorator Works

The built-in property() function creates a descriptor object. This object has three methods:

  • getter: A function that returns the value of the property.
  • setter: A function that sets the value of the property.
  • deleter: A function that deletes the property.

When used as a decorator, property() takes a function as its argument. This function becomes the getter for the property.

How the Decorator @property Works

The @property decorator is just syntactic sugar for the following code:

def foo(self): return self._foo
foo = property(foo)

The @decorator syntax replaces the function being decorated with the special property() descriptor object.

Creating Properties with Decorators

To create properties with decorators:

class C:
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
  • The @property decorator creates a getter function and attaches it to the _x property.
  • The @x.setter decorator creates a new property object, replacing the getter with the decorated setter function.
  • The @x.deleter decorator creates a new property object, replacing the getter with the decorated deleter function.

In-Depth Understanding

The property() function returns a special descriptor object. This object has extra methods, including getter, setter, and deleter. These methods are also decorators, which allow you to incrementally construct a full-on property object.

The syntax of the property decorator allows you to create properties with chained setter and deleter decorators. The resulting property object is then attached to the class as a descriptor, enabling attribute getting, setting, and deletion with custom behavior.

The above is the detailed content of How Does the `@property` Decorator Function in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn