Python property(): How to Use property() Function In Python

The property() constructs in Python returns the property attribute.

Python property()

Python property() is an inbuilt function that returns a property attribute. The property() method delivers the property attribute from a given getter, setter, and deleter. If no arguments are given, the property() method returns the base property attribute that doesn’t include any getter, setter, or deleter. If the doc isn’t provided, the property() method takes the docstring of the getter function.

Syntax

The syntax of the Python property() method is the following.

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

Parameters: The property() method takes four optional parameters:

  1. fget (Optional) – This function for getting the attribute value.
  2. fset (Optional) – This function for setting the attribute value.
  3. fdel (Optional) – This function for deleting the attribute value.
  4. doc (Optional) – The string that contains the documentation (docstring) for the attribute.


Return: Returns a property attribute from the given getter, setter and deleter.


Python property() function Example

class Example:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        print('Getting name')
        return self._name

    @name.setter
    def name(self, value):
        print('Setting name to ' + value)
        self._name = value

    @name.deleter
    def name(self):
        print('Deleting name')
        del self._name

x = Example('Toms')
print('The name is:', x.name)

x.name = 'Jacks'

del x.name

Output:

Getting name
The name is: Toms
Setting name to Jacks
Deleting name

#python #python property

Python property(): How to Use property() Function In Python
1.75 GEEK