python


Python property() function

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:
fget() – used to get the value of attribute
fset() – used to set the value of attribute
fdel() – used to delete the attribute value
doc() – string that contains the documentation (docstring) for the attribute
Return: Returns a property attribute from the given getter, setter and deleter
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.
Example:

# 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:
The main work of decorators is they are used to add functionality to the existing code. Also called metaprogramming, as a part of the program tries to modify another part of the program at compile time.
Example: Using @property 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.


Morty Proxy This is a proxified and sanitized view of the page, visit original site.