The property()
function in Python creates and returns a property object. Properties are special attributes that allow the user to define getter, setter, and deleter methods for a class attribute. This function is typically used as a decorator to define properties in a more readable and concise way.
Parameter Values
Parameter | Description |
---|---|
fget | Function to retrieve the attribute value |
fset | Function to set the attribute value |
fdel | Function to delete the attribute value |
doc | Docstring for the attribute |
Return Values
The property()
function returns a property
object that can encapsulate getter, setter, and deleter methods.
How to Use property()
in Python
The property()
function returns a property attribute for a new-style class. It takes four optional parameters: fget
, fset
, fdel
, and doc
.
class Celsius:
def __init__(self, temperature=0):
self._temperature = temperature
def get_temperature(self):
return self._temperature
def set_temperature(self, value):
if value < -273.15:
raise ValueError('Temperature below -273.15 is not possible')
self._temperature = value
temperature = property(get_temperature, set_temperature)
The property()
function can also be used as a decorator. In this case, the getter method returns the value directly, and there is no setter method defined.
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14 * self._radius**2
The property()
function can be used with only a getter method to create a read-only attribute.
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name