Python property()
The property()
function in Python is used to create and return a property object. It allows defining a method as a getter, setter or a deleter of an attribute.
Syntax:
property(fget=None, fset=None, fdel=None, doc=None)
Parameters:
- fget
: Optional. A method to get the value of the attribute.
- fset
: Optional. A method to set the value of the attribute.
- fdel
: Optional. A method to delete the attribute.
- doc
: Optional. A string to provide the documentation for the attribute.
Return value:
- A property object that can be assigned to a class attribute. When accessed, the methods defined by fget
, fset
, and fdel
will be called accordingly.
Example usage:
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:
self._radius = value
else:
raise ValueError("Radius cannot be negative!")
@radius.deleter
def radius(self):
del self._radius
# Creating an instance of Circle
c = Circle(5)
# Accessing the radius attribute using the property
print(c.radius) # Output: 5
# Setting a new value to the radius attribute
c.radius = 10
print(c.radius) # Output: 10
# Trying to set a negative value to the radius attribute
c.radius = -5 # Raises a ValueError
# Deleting the radius attribute
del c.radius
print(c.radius) # AttributeError: 'Circle' object has no attribute '_radius'
In the above example, @property
decorator is used to define a getter method for the radius
attribute, @radius.setter
decorator is used to define a setter method, and @radius.deleter
decorator is used to define a deleter method.