Python property()

Python property() builtin function is used to get the property attribute and we can optionally provide functions to get, set or delete the attribute value.

In this tutorial, we will learn about the syntax of Python property() function, and learn how to use this function with the help of examples.

Syntax

The syntax of property() function is

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

where

ParameterRequired/OptionalDescription
fgetOptionalA function. This function gets the attribute value. Default value is None.
fsetOptionalA function. This function sets the attribute value. Default value is None.
fdelOptionalA function. This function deletes the attribute value. Default value is None.
docOptionalA string. Doc string for the attribute. Default value is None.

Returns

The function returns property attribute formed by given getter, setter and delete functions.

Example

In this example, we will

Python Program

class A:
    def __init__(self, x):
        self._x = x

    def get_x(self):
        return self._x

    def set_x(self, x):
        self._x = x

    def del_x(self):
        del self._x
    
    x = property(get_x, set_x, del_x, 'X property')

    
obj = A(99)

#get attribute value
value = obj.x
print(value)

#set attribute value
obj.x = 55
print(obj.x)

#del attribute value
del obj.x
Try Online

Output

99
55

Conclusion

In this Python Tutorial, we have learnt the syntax of Python property() builtin function, and also learned how to use this function, with the help of Python example programs.