In Python, the main purpose of Property() function is to create property of a class.
Syntax:
property(fget, fset, fdel, doc)
If no arguments are given, property() method returns a base property attribute that doesn’t contain any getter, setter or deleter.
If doc isn’t provided, property() method takes the docstring of the getter function.
Parameters:
# Python program to explain property() function
# Alphabet class
class Alphabet:
def __init__(self, value):
self._value = value
# getting the values
def getValue(self):
print('Getting value')
return self._value
# setting the values
def setValue(self, value):
print('Setting value to ' + value)
self._value = value
# deleting the values
def delValue(self):
print('Deleting value')
del self._value
value = property(getValue, setValue, delValue, )
# passing the value
x = Alphabet('CODEMISTIC')
print(x.value)
x.value = 'CM'
del x.value
Output:
Getting value
CODEMISTIC
Setting value to CM
Deleting value
Using Decorator:
# Python program to explain property()
# function using decorator
class Alphabet:
def __init__(self, value):
self._value = value
# getting the values
@property
def value(self):
print('Getting value')
return self._value
# setting the values
@value.setter
def value(self, value):
print('Setting value to ' + value)
self._value = value
# deleting the values
@value.deleter
def value(self):
print('Deleting value')
del self._value
# passing the value
x = Alphabet('Peter')
print(x.value)
x.value = 'Diesel'
del x.value
Output:
Getting value
Peter
Setting value to Diesel
Deleting value
Applications:
By using property() method, we can modify our class and implement the value constraint without any change required to the client code. So that the implementation is backward compatible.