property(fget=None, fset=None, fdel=None, doc=None)
The property() function returns a property attribute.
Parameters
The property() function takes four optional parameters:
fget— function for getting the attribute value. Defaults to None.fset— function for setting the attribute value. Defaults to None.fdel— function for deleting the attribute value. Defaults to None.doc— string containing the documentation (docstring) for the attribute. Defaults toNone.
Return Value
The property() function returns a property attribute from the given getter, setter, and deleter methods.
- If no arguments are specified,
property()returns a base property attribute without any getter, setter, or deleter methods. - If
docis not specified,property()uses the documentation string from the getter function.
Examples
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
print('Getting name')
return self._name
def set_name(self, value):
print(f'Setting name to {value}')
self._name = value
def del_name(self):
print('Deleting name')
del self._name
# Set property to use get_name, set_name, and del_name methods
name = property(get_name, set_name, del_name, 'Property name')
p = Person('John')
print(p.name)
p.name = 'Michael'
del p.name
# Output
Getting name
John
Setting name to Michael
Deleting name