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
</>
Copy
property(fget=None, fset=None, fdel=None, doc=None)
where
Parameter | Required/ Optional | Description |
---|---|---|
fget | Optional | A function. This function gets the attribute value. Default value is None. |
fset | Optional | A function. This function sets the attribute value. Default value is None. |
fdel | Optional | A function. This function deletes the attribute value. Default value is None. |
doc | Optional | A 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 create a class A
, and in this class we use property() method.
Python Program
</>
Copy
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
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.