pythonpropertiesdecorator

Need help on @property in python


I have a class as shown with @property decorator and some methods.

class Alphabet:

    def __init__(self, value):
        self._value = value

    # getting the values
    @property
    def v(self):
        print('Getting value')
        return self._value

    # setting the values
    @v.setter
    def v(self, value):
        print('Setting value to ' + value)
        self._value = value

    # deleting the values
    @v.deleter
    def value(self):
        print('Deleting value')
        del self._value

# passing the value

x = Alphabet('Peter')

print(x.value)

x.value = 'Diesel'

This gives me output as shown:

Getting value
Peter
Setting value to Diesel

How this is possible as the "value" function is not defined to get the value or set the value


Solution

  • Yes, value is defined with a getter and a setter. Your class actually has two properties: one named v, which has a getter and setter, and one named value, which has the same getter and setter as v in addition to a deleter. Take a look at the same class without using decorators:

    class Alphabet:
    
        def __init__(self, value):
            self._value = value
    
        def v(self):
            print('Getting value')
            return self._value
    
        v = property(v)
    
        # slight renaming to avoid prematurely overwriting the existing property
        def _v(self, value):
            print('Setting value to ' + value)
            self._value = value
        v = v.setter(_v); del _v
    
        def value(self):
            print('Deleting value')
            del self._value
    
        value = v.deleter(value)
    

    v.getter and v.setter do not modify an existing property in-place; they create and return new properties based on v. In the end, you finally decorated a function named value, so that's the name the final property was assigned to.