The property() function is one of Python's built-in functions used to create properties, allowing methods to be accessed like attributes.
Function Syntax
property(fget=None, fset=None, fdel=None, doc=None)
Parameters:
fget: Function to get attribute value.fset: Function to set attribute value.fdel: Function to delete attribute.doc: Documentation string for the property.
The property() function returns a property object that can be assigned to a class attribute. When accessing this attribute, it automatically calls one or more of the fget, fset, and fdel functions to implement getting, setting, and deleting property values.
property() Function Examples
class Data:
def __init__(self, value):
self._private_value = value
def get_value(self):
return self._private_value
def set_value(self, value):
self._private_value = value
def del_value(self):
del self._private_value
x = property(get_value, set_value, del_value, "This is a description of x")
data = Data(123)
# Actually calls data.get_value()
print(data.x) # Output: 123
# Actually calls data.set_value()
data.x = 1
print(data.x) # Output: 1
# Actually calls data.del_value()
del data.x
@property Decorator
The @property decorator is a special function that converts methods into properties:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
return 3.14 * self._radius ** 2
a = Circle(5)
print(a.area) # Output: 78.5
a.radius = 10
print(a.area) # Output: 314.0